<?php
// Register.php
session_start();
require_once "db_central.php"; // <-- make sure this file has $conn = new mysqli(...);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Collect & sanitize inputs
    $first_name   = trim($_POST['first_name'] ?? '');
    $last_name    = trim($_POST['last_name'] ?? '');
    $email        = trim($_POST['email'] ?? '');
    $password     = $_POST['password'] ?? '';
    $confirm_pass = $_POST['confirm_password'] ?? '';
    $role         = $_POST['role'] ?? '';
    $department   = trim($_POST['department'] ?? '');
    $phone        = trim($_POST['phone_number'] ?? '');

    // Basic validations
    if (empty($first_name) || empty($last_name) || empty($email) || empty($password) || empty($confirm_pass) || empty($role)) {
        $_SESSION['error'] = "All required fields must be filled.";
        header("Location: register_form.php"); // <-- your HTML form page
        exit();
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $_SESSION['error'] = "Invalid email format.";
        header("Location: register_form.php");
        exit();
    }

    // Enforce email domain constraint
    if (!str_ends_with($email, "@cs.unza.zm")) {
        $_SESSION['error'] = "Email must be an @cs.unza.zm address.";
        header("Location: register_form.php");
        exit();
    }

    if ($password !== $confirm_pass) {
        $_SESSION['error'] = "Passwords do not match.";
        header("Location: register_form.php");
        exit();
    }

    if (strlen($password) < 8) {
        $_SESSION['error'] = "Password must be at least 8 characters.";
        header("Location: register_form.php");
        exit();
    }

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

    // Generate UUID (MySQL >= 8 has UUID(), but we can generate in PHP)
    $user_id = bin2hex(random_bytes(16));
    $user_id = substr($user_id, 0, 8) . "-" . substr($user_id, 8, 4) . "-" . substr($user_id, 12, 4) . "-" . substr($user_id, 16, 4) . "-" . substr($user_id, 20);

    // Insert user
    $stmt = $conn->prepare("INSERT INTO users (user_id, email, password_hash, first_name, last_name, role, department, phone_number) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssssss", $user_id, $email, $password_hash, $first_name, $last_name, $role, $department, $phone);

    if ($stmt->execute()) {
        $_SESSION['success'] = "Account created successfully. Please log in.";
        header("Location: login.php");
        exit();
    } else {
        if ($conn->errno === 1062) {
            $_SESSION['error'] = "An account with this email already exists.";
        } else {
            $_SESSION['error'] = "Error: " . $conn->error;
        }
        header("Location: register_form.php");
        exit();
    }
}
?>