<?php
session_start();

// Database connection
$conn = new mysqli("localhost", "kkfxoaad", "Bitok@2025", "kkfxoaad_bella");

// Check connection
if ($conn->connect_error) {
    die("Database connection failed: " . $conn->connect_error);
}

// Only handle POST requests
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $firstName = trim($_POST['firstName']);
    $lastName  = trim($_POST['lastName']);
    $email     = trim($_POST['email']);
    $phone     = trim($_POST['phone']);
    $password  = $_POST['password'];

    // Validate inputs
    if (empty($firstName) || empty($lastName) || empty($email) || empty($phone) || empty($password)) {
        die("All fields are required.");
    }

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

    if ($stmt->num_rows > 0) {
        die("Email already registered. <a href='login.php'>Login here</a>");
    }
    $stmt->close();

    // Hash password securely
    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

    // Insert new user
    $stmt = $conn->prepare("INSERT INTO users (firstName, lastName, phone, email, password, profile_pic, is_admin) 
                            VALUES (?, ?, ?, ?, ?, 'images/default-user.png', 0)");
    $stmt->bind_param("sssss", $firstName, $lastName, $phone, $email, $hashedPassword);

    if ($stmt->execute()) {
        // Redirect to login after successful registration
        header("Location: login.php?registered=1");
        exit;
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
}

$conn->close();
?>
