<?php
/**
 * Register Handler
 * Process user registration
 */

header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/session.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$response = ['success' => false, 'message' => ''];

try {
    // Get POST data
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // Validation
    if (empty($first_name) || empty($last_name)) {
        throw new Exception('First and last names are required');
    }
    
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new Exception('Valid email address is required');
    }
    
    if (empty($password) || strlen($password) < 6) {
        throw new Exception('Password must be at least 6 characters');
    }
    
    if ($password !== $confirm_password) {
        throw new Exception('Passwords do not match');
    }

    // Check if email already exists
    $check_sql = "SELECT id FROM users WHERE email = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param('s', $email);
    $check_stmt->execute();
    $check_stmt->store_result();

    if ($check_stmt->num_rows > 0) {
        throw new Exception('Email address already registered');
    }

    // Hash password
    $hashed_password = password_hash($password, PASSWORD_BCRYPT);

    // Insert user
    $insert_sql = "INSERT INTO users (first_name, last_name, email, password, user_type, is_active) 
                   VALUES (?, ?, ?, ?, 'guest', 1)";
    $insert_stmt = $conn->prepare($insert_sql);
    $insert_stmt->bind_param('ssss', $first_name, $last_name, $email, $hashed_password);

    if ($insert_stmt->execute()) {
        $user_id = $insert_stmt->insert_id;
        loginUser($user_id, $email, $first_name, $last_name, 'guest');
        
        $response['success'] = true;
        $response['message'] = 'Registration successful! Redirecting...';
        $response['redirect'] = 'index.php';
    } else {
        throw new Exception('Failed to create account');
    }

} catch (Exception $e) {
    http_response_code(400);
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
$conn->close();
?>
