<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

define("ROOT", $_SERVER['DOCUMENT_ROOT'] . "/SEAT");
include(ROOT . "/config/db.php");

header('Content-Type: application/json');

/* =====================================
   RESPONSE HELPER
===================================== */
function jsonResponse($status, $message){
    echo json_encode([
        "status" => $status,
        "message" => $message
    ]);
    exit;
}



/* =====================================
   INPUT HELPERS
===================================== */
function clean($value){
    return trim($value);
}

function digitsOnly($value){
    return preg_replace('/\D/', '', $value);
}

function upper($value){
    return strtoupper(trim($value));
}

function lower($value){
    return strtolower(trim($value));
}




/* =====================================
   DB EXISTS CHECK
===================================== */
function exists($conn, $query, $types, ...$params){

    $stmt = mysqli_prepare($conn, $query);
    if(!$stmt){
        jsonResponse("error", "Database error");
    }

    mysqli_stmt_bind_param($stmt, $types, ...$params);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);

    $result = mysqli_stmt_num_rows($stmt) > 0;

    mysqli_stmt_close($stmt);
    return $result;
}




/* =====================================
   ROLE VALIDATION
===================================== */
$role = $_POST['role'] ?? '';

$roles = ["student", "staff", "organizer"];
if(!in_array($role, $roles)){
    jsonResponse("error", "Invalid role");
}




/* =====================================
   INPUT COLLECTION (CLEAN)
===================================== */
$full         = clean($_POST['user_full_name'] ?? '');
$club_name    = clean($_POST['club_name'] ?? '');
$email        = lower($_POST['user_email'] ?? '');
$phone        = digitsOnly($_POST['user_phone'] ?? '');
$matric       = upper($_POST['matric'] ?? '');
$faculty      = clean($_POST['faculty'] ?? '');

$club_type    = clean($_POST['club_type'] ?? '');
$advisor_name = clean($_POST['advisor_name'] ?? '');
$advisor_phone= digitsOnly($_POST['advisor_phone_unique'] ?? '');
$description  = clean($_POST['description'] ?? '');

$bank_holder  = clean($_POST['account_holder_name'] ?? '');
$bank_name    = clean($_POST['bank_name'] ?? '');
$bank_account = digitsOnly($_POST['account_number'] ?? '');

/* organizer override */
if($role === "organizer"){
    $full = $club_name;
}



/* =====================================
   ERROR COLLECTOR
===================================== */
$errors = [];

/* =====================================
   EMAIL VALIDATION
===================================== */
$emailRules = [
    "student"   => '/^[a-zA-Z0-9._%+-]+@student\.usm\.my$/',
    "staff"     => '/^[a-zA-Z0-9._%+-]+@usm\.my$/',
    "organizer" => '/^[a-zA-Z0-9._%+-]+@gmail\.com$/'
];

if(!preg_match($emailRules[$role], $email)){
    $errors[] = "Invalid email domain";
}

/* duplicate email */
if(exists($conn, "SELECT id FROM users WHERE email = ?", "s", $email)){
    $errors[] = "Email already exists";
}

/* =====================================
   PASSWORD (non-organizer)
===================================== */
$password = "";
$status = ($role === "organizer") ? "pending" : "active";

if($role !== "organizer"){

    $pass = $_POST['user_password'] ?? '';
    $confirm = $_POST['user_confirm_password'] ?? '';

    if($pass !== $confirm){
        $errors[] = "Passwords do not match";
    }

    $strong =
        strlen($pass) >= 7 &&
        preg_match('/[A-Z]/', $pass) &&
        preg_match('/[a-z]/', $pass) &&
        preg_match('/[0-9]/', $pass) &&
        preg_match('/[\W]/', $pass);

    if(!$strong){
        $errors[] = "Weak password";
    }

    if(empty($errors)){
        $password = password_hash($pass, PASSWORD_DEFAULT);
    }
}



/* =====================================
   ROLE VALIDATION
===================================== */
if($role === "student"){

    if(!preg_match('/^[0-9]{6}$/', $matric)){
        $errors[] = "Invalid matric number";
    }

    if(empty($faculty)){
        $errors[] = "Faculty required";
    }

    if(exists($conn,
        "SELECT id FROM participants WHERE matric_no = ?",
        "s", $matric)){
        $errors[] = "Matric already exists";
    }
}

if($role === "staff"){

    if(!preg_match('/^[A-Z]{2}[0-9]{4}$/', $matric)){
        $errors[] = "Invalid staff ID";
    }

    if(exists($conn,
        "SELECT id FROM participants WHERE staff_no = ?",
        "s", $matric)){
        $errors[] = "Staff ID already exists";
    }
}



/* =====================================
   PHONE VALIDATION
===================================== */
if($role !== "organizer"){

    if(!preg_match('/^01[0-9]{8,9}$/', $phone)){
        $errors[] = "Invalid phone number";
    }

    if(exists($conn,
        "SELECT id FROM participants WHERE phone = ?
         UNION
         SELECT id FROM organizers WHERE advisor_phone = ?",
        "ss", $phone, $phone)){
        $errors[] = "Phone already exists";
    }
}



/* =====================================
   ORGANIZER VALIDATION
===================================== */
if($role === "organizer"){

    if(empty($club_name)) $errors[] = "Club name required";
    if(empty($advisor_name)) $errors[] = "Advisor name required";

    if(!preg_match('/^01[0-9]{8,9}$/', $advisor_phone)){
        $errors[] = "Invalid advisor phone";
    }

    if(empty($bank_holder)) $errors[] = "Bank holder required";
    if(empty($bank_name)) $errors[] = "Bank name required";

    if(empty($bank_account)){
        $errors[] = "Invalid bank account number";
    }
}

/* =====================================
   STOP IF ERRORS
===================================== */
if($errors){
    jsonResponse("error", implode("<br>", $errors));
}



/* =====================================
   FILE UPLOAD 
===================================== */
$document = "";

if(!empty($_FILES['file']['name'])){

    $file = $_FILES['file'];

    if($file['error'] !== 0){
        jsonResponse("error", "Upload failed");
    }

    if($file['size'] > 5 * 1024 * 1024){
        jsonResponse("error", "Max 5MB only");
    }

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    if($ext !== "pdf"){
        jsonResponse("error", "Only PDF allowed");
    }

    $document = time() . "_" . preg_replace("/[^a-zA-Z0-9.]/", "_", $file['name']);

    $path = ROOT . "/uploads/club_register/" . $document;

    if(!move_uploaded_file($file['tmp_name'], $path)){
        jsonResponse("error", "Upload failed");
    }
}




/* =====================================
   INSERT USER
===================================== */
$stmt = mysqli_prepare($conn,
    "INSERT INTO users (email, password, role, status)
     VALUES (?, ?, ?, ?)"
);

mysqli_stmt_bind_param($stmt, "ssss",
    $email, $password, $role, $status
);

mysqli_stmt_execute($stmt);
$user_id = mysqli_insert_id($conn);
mysqli_stmt_close($stmt);





/* =====================================
   PARTICIPANT / ORGANIZER INSERT
===================================== */
if($role === "student" || $role === "staff"){

    $matric_no = $role === "student" ? $matric : null;
    $staff_no  = $role === "staff" ? $matric : null;
    if($role === "staff") $faculty = null;

    $stmt = mysqli_prepare($conn,
        "INSERT INTO participants
        (user_id, full_name, matric_no, staff_no, faculty, phone)
        VALUES (?, ?, ?, ?, ?, ?)"
    );

    mysqli_stmt_bind_param($stmt, "isssss",
        $user_id, $full, $matric_no, $staff_no, $faculty, $phone
    );

    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
}

if($role === "organizer"){

    $stmt = mysqli_prepare($conn,
        "INSERT INTO organizers
        (user_id, club_name, club_type, advisor_name, advisor_phone, description, document)
        VALUES (?, ?, ?, ?, ?, ?, ?)"
    );

    mysqli_stmt_bind_param($stmt, "issssss",
        $user_id, $club_name, $club_type,
        $advisor_name, $advisor_phone,
        $description, $document
    );

    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);

    $stmt = mysqli_prepare($conn,
        "INSERT INTO bank_accounts
        (user_id, bank_name, account_holder_name, account_number, updated_by)
        VALUES (?, ?, ?, ?, ?)"
    );

    mysqli_stmt_bind_param($stmt, "issss",
        $user_id, $bank_name, $bank_holder, $bank_account, $full
    );

    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
}



/* =====================================
   RESPONSE
===================================== */
jsonResponse("success",
    $role === "organizer"
        ? "Account submitted. Waiting approval."
        : "Registration successful"
);
?>