<?php
session_start();
require_once 'config/database.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: register.php');
    exit;
}

$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$confirm = $_POST['confirm_password'] ?? '';

$errors = [];

if (empty($name)) $errors[] = 'Name is required.';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email is required.';
if (strlen($password) < 6) $errors[] = 'Password must be at least 6 characters.';
if ($password !== $confirm) $errors[] = 'Passwords do not match.';

if (!empty($errors)) {
    $_SESSION['register_error'] = implode('<br>', $errors);
    header('Location: register.php');
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    if ($stmt->fetch()) {
        $_SESSION['register_error'] = 'Email already registered.';
        header('Location: register.php');
        exit;
    }

    $hashed = password_hash($password, PASSWORD_DEFAULT);
    // Insert with email_verified = 1 (no verification needed)
    $stmt = $pdo->prepare("INSERT INTO users (name, email, password, email_verified) VALUES (?, ?, ?, 1)");
    $stmt->execute([$name, $email, $hashed]);

    $_SESSION['register_success'] = 'Registration successful! You can now login.';
    header('Location: index.php');
} catch (PDOException $e) {
    error_log("Registration error: " . $e->getMessage());
    $_SESSION['register_error'] = 'An error occurred. Please try again.';
    header('Location: register.php');
}
?>