<?php
require_once __DIR__ . "/../config.php";

$first = trim($_POST['first_name'] ?? "");
$last  = trim($_POST['last_name'] ?? "");
$email = trim($_POST['email'] ?? "");
$pass  = trim($_POST['password'] ?? "");
$pass2 = trim($_POST['confirm_password'] ?? "");

/* Validate */
if ($first=="" || $last=="" || $email=="" || $pass=="" || $pass2=="") {
    fxh_set_flash("All fields are required.");
    header("Location: register.php");
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    fxh_set_flash("Invalid email address.");
    header("Location: register.php");
    exit;
}

if ($pass !== $pass2) {
    fxh_set_flash("Passwords do not match.");
    header("Location: register.php");
    exit;
}

/* Duplicate check */
$chk = $conn->prepare("SELECT id FROM fxh_users WHERE email=?");
$chk->bind_param("s",$email);
$chk->execute();
$chk->store_result();

if($chk->num_rows){
    fxh_set_flash("Email already registered. Please login.");
    header("Location: /portal/login.php");
    exit;
}

/* Create user */
$hash = password_hash($pass, PASSWORD_DEFAULT);

$stmt = $conn->prepare("
    INSERT INTO fxh_users(first_name,last_name,email,password_hash)
    VALUES(?,?,?,?)
");
$stmt->bind_param("ssss",$first,$last,$email,$hash);

if(!$stmt->execute()){
    fxh_set_flash("Account creation failed.");
    header("Location: register.php");
    exit;
}

/* Auto-login */
$_SESSION['user_id'] = $stmt->insert_id;
$_SESSION['email']   = $email;

fxh_set_flash("Account created successfully ✅","success");

header("Location: /portal/dashboard.php");
exit;
