<?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
===================================== */
function jsonResponse($status, $message){

    echo json_encode([
        "status"  => $status,
        "message" => $message
    ]);

    exit;
}

/* =====================================
   SANITIZE
===================================== */
function clean($conn, $value){

    return mysqli_real_escape_string(
        $conn,
        trim($value)
    );
}

/* =====================================
   CHECK EXIST
===================================== */
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);

    $exists = mysqli_stmt_num_rows($stmt) > 0;

    mysqli_stmt_close($stmt);

    return $exists;
}

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

$allowedRoles = ["student", "staff", "organizer"];

if(!in_array($role, $allowedRoles)){
    jsonResponse("error", "Invalid role");
}

/* =====================================
   INPUT
===================================== */
$full           = clean($conn, $_POST['user_full_name'] ?? '');
$club_name      = clean($conn, $_POST['club_name'] ?? '');
$email          = strtolower(clean($conn, $_POST['user_email'] ?? ''));
$phone          = preg_replace('/\D/', '', $_POST['user_phone'] ?? '');
$matric         = strtoupper(clean($conn, $_POST['matric'] ?? ''));
$faculty        = clean($conn, $_POST['faculty'] ?? '');

$club_type      = clean($conn, $_POST['club_type'] ?? '');
$advisor_name   = clean($conn, $_POST['advisor_name'] ?? '');
$advisor_phone  = preg_replace('/\D/', '', $_POST['advisor_phone_unique'] ?? '');
$description    = clean($conn, $_POST['description'] ?? '');

$bank_holder    = clean($conn, $_POST['account_holder_name'] ?? '');
$bank_name      = clean($conn, $_POST['bank_name'] ?? '');
$bank_account   = preg_replace('/\D/', '', $_POST['account_number'] ?? '');

$errors = [];

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

/* =====================================
   EMAIL VALIDATION
===================================== */
function validEmail($email, $role){

    switch($role){

        case "student":
            return preg_match(
                '/^[a-zA-Z0-9._%+-]+@student\.usm\.my$/',
                $email
            );

        case "staff":
            return preg_match(
                '/^[a-zA-Z0-9._%+-]+@usm\.my$/',
                $email
            );

        case "organizer":
            return preg_match(
                '/^[a-zA-Z0-9._%+-]+@gmail\.com$/',
                $email
            );
    }

    return false;
}

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

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

/* =====================================
   PASSWORD
===================================== */
$password = "";
$status   = "active";

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

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

    if($pass !== $confirm){
        $errors[] = "Password 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 (min 7 char, uppercase, lowercase, number, symbol)";
    }

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

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

    if(!preg_match('/^[0-9]{6}$/', $matric)){
        $errors[] = "Student matric must be 6 digits";
    }

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

/* =====================================
   STAFF VALIDATION
===================================== */
if($role === "staff"){

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

/* =====================================
   STUDENT MATRIC DUPLICATE
===================================== */
if($role === "student"){

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

/* =====================================
   STAFF ID DUPLICATE
===================================== */
if($role === "staff"){

    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 number already exists";
    }
}

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

    $status = "pending";

    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(
        exists(
            $conn,
            "
            SELECT id
            FROM organizers
            WHERE advisor_phone = ?

            UNION

            SELECT id
            FROM participants
            WHERE phone = ?
            ",
            "ss",
            $advisor_phone,
            $advisor_phone
        )
    ){
        $errors[] = "Advisor phone already exists";
    }

    if(empty($bank_holder)){
        $errors[] = "Bank holder required";
    }

    if(empty($bank_name)){
        $errors[] = "Bank name required";
    }

    if(
        empty($bank_account) ||
        !preg_match('/^[0-9]+$/', $bank_account)
    ){
        $errors[] = "Invalid bank account number";
    }
}

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

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

if(
    isset($_FILES['file']) &&
    $_FILES['file']['name'] !== ""
){

    $file = $_FILES['file'];

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

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

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

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

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

    $document = time() . "_" . $cleanName;

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

    if(!move_uploaded_file($file['tmp_name'], $uploadPath)){
        jsonResponse("error", "Failed to upload file");
    }
}

/* =====================================
   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);

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

    $matric_no = NULL;
    $staff_no  = NULL;

    if($role === "student"){
        $matric_no = $matric;
    }

    if($role === "staff"){
        $staff_no = $matric;
        $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);
}

/* =====================================
   INSERT ORGANIZER
===================================== */
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);

    /* =========================
       BANK ACCOUNT
    ========================= */
    $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);
}

/* =====================================
   SUCCESS RESPONSE
===================================== */
$message =
    ($role === "organizer")
    ? "Account submitted. Waiting admin approval."
    : "Registration successful";

jsonResponse("success", $message);
?>