<?php
require_once __DIR__ . '/../config/db_connect.php'; // Database connection

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

$errors = [];
$email = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate email
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format.";
    }

    // Validate password
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if (empty($password)) {
        $errors[] = "Password is required.";
    } elseif (strlen($password) < 8) { // Basic password length check
        $errors[] = "Password must be at least 8 characters long.";
    } elseif ($password !== $confirm_password) {
        $errors[] = "Passwords do not match.";
    }

    // Check if terms are accepted
    $terms_accepted = isset($_POST['terms_accepted']) && $_POST['terms_accepted'] === 'on';
    if (!$terms_accepted) {
        $errors[] = "You must accept the Terms of Service to create an account.";
    }

    // If no validation errors, proceed to check database
    if (empty($errors)) {
        // Check if email already exists
        $stmt = $mysqli->prepare("SELECT id FROM users WHERE email = ?");
        if ($stmt) {
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();

            if ($stmt->num_rows > 0) {
                $errors[] = "Email address is already registered.";
            }
            $stmt->close();
        } else {
            $errors[] = "Database error: Could not prepare statement.";
            // Log $mysqli->error for debugging
        }
    }

    // If still no errors, create user
    if (empty($errors)) {
        $password_hash = password_hash($password, PASSWORD_DEFAULT);

        $stmt = $mysqli->prepare("INSERT INTO users (email, password_hash) VALUES (?, ?)");
        if ($stmt) {
            $stmt->bind_param("ss", $email, $password_hash);
            if ($stmt->execute()) {
                // Registration successful
                // Optionally, log the user in directly
                // $_SESSION['user_id'] = $stmt->insert_id;
                // $_SESSION['email'] = $email;
                // header("Location: dashboard.php");

                // Or redirect to login page with a success message
                $_SESSION['success_message'] = "Registration successful! Please login.";
                header("Location: login.php");
                exit();
            } else {
                $errors[] = "Registration failed. Please try again.";
                // Log $stmt->error for debugging
            }
            $stmt->close();
        } else {
            $errors[] = "Database error: Could not prepare insert statement.";
            // Log $mysqli->error for debugging
        }
    }
}
?>

<?php
require_once __DIR__ . '/../includes/header.php';   // HTML header
?>

<div class="form-container">
    <h2>Register</h2>

    <?php if (!empty($errors)): ?>
        <div class="errors">
            <?php foreach ($errors as $error): ?>
                <p><?php echo htmlspecialchars($error); ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <form action="register.php" method="POST">
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email); ?>" required>
        </div>
        <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
            <small>Password must be at least 8 characters.</small>
        </div>
        <div class="form-group">
            <label for="confirm_password">Confirm Password:</label>
            <input type="password" id="confirm_password" name="confirm_password" required>
        </div>
        
        <div class="form-group checkbox-group">
            <input type="checkbox" id="terms_accepted" name="terms_accepted" required>
            <label for="terms_accepted">
                I agree to the <a href="terms.php" target="_blank">Terms of Service</a> and <a href="privacy.php" target="_blank">Privacy Policy</a>
            </label>
        </div>
        
        <button type="submit" class="button">Register</button>
    </form>
    <p>Already have an account? <a href="login.php">Login here</a>.</p>
</div>

<?php
$mysqli->close();
require_once __DIR__ . '/../includes/footer.php'; // HTML footer
?>
