<?php
// process_register.php
//echo "Hello";
session_start();
require_once 'config.php';
require_once 'includes/auth.php';
require_once 'classes/User.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and validate input
    $first_name_en = trim($_POST['first_name_en'] ?? '');
    $last_name_en = trim($_POST['last_name_en'] ?? '');
    $sex = trim($_POST['sex'] ?? '');
    $dob = trim($_POST['dob'] ?? '');
    $phone_number = trim($_POST['phone_number'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Basic validation
    if (empty($first_name_en) || empty($last_name_en) || empty($sex) || empty($dob) || empty($username) || empty($password) || empty($confirm_password)) {
        set_message("All required fields must be filled.", "danger");
        header("Location: index.php");
        exit();
    }

    if ($password !== $confirm_password) {
        set_message("Passwords do not match.", "danger");
        header("Location: index.php");
        exit();
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($email)) {
        set_message("Invalid email format.", "danger");
        header("Location: index.php");
        exit();
    }

    // Prepare data for User class
    $person_data = [
        'id_card' => null,
        'first_name_en' => $first_name_en,
        'last_name_en' => $last_name_en,
        'sex' => $sex,
        'dob' => $dob,
        'pob' => null, // Add if you collect this
        'nationality' => 'Cambodian', // Default or collect
        'marital_status' => 'Single', // Default or collect
        'phone_number' => $phone_number,
        'email' => $email,
        'telegram' => null, // Add if you collect this
        'note' => null // Add if you collect this
    ];

    $user_data = [
        'username' => $username,
        'password' => $password,
        'status' => 'Data User' // Default status for new registrations
    ];

    $user_manager = new User($pdo);

    if ($user_manager->registerUser($person_data, $user_data)) {
        set_message("Registration successful! You can now log in.", "success");
        header("Location: index.php");
        exit();
    } else {
        // Error message is set within registerUser for specific duplicate cases
        // If it's a generic DB error, a message is already set.
        if (!isset($_SESSION['message'])) {
             set_message("Registration failed due to an unexpected error. Please try again.", "danger");
        }
        header("Location: index.php");
        exit();
    }
} else {
    // Not a POST request, redirect to home
    header("Location: index.php");
    exit();
}
?>
