<?php
session_start();
include($_SERVER['DOCUMENT_ROOT']."/SEAT/config/db.php");

require_once $_SERVER['DOCUMENT_ROOT']."/SEAT/modules/Notification/registrationEmail.php";
require_once $_SERVER['DOCUMENT_ROOT']."/SEAT/modules/Notification/notification_helper.php";

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

/* ================= SESSION CHECK ================= */
if(!isset($_SESSION['id'])){
    echo json_encode(["error"=>"Session expired"]);
    exit;
}

$user_id = (int)$_SESSION['id'];
$role    = $_SESSION['role'] ?? '';

$data = json_decode(file_get_contents("php://input"), true);
$event_id = (int)($data['event_id'] ?? 0);

if($event_id <= 0){
    echo json_encode(["error"=>"Invalid event"]);
    exit;
}

/* ================= LOAD EVENT ================= */
$stmt = $conn->prepare("
SELECT 
    e.*,
    o.club_name,
    b.account_holder_name,
    b.bank_name,
    b.account_number
FROM events e
LEFT JOIN organizers o ON e.organizer_id = o.id
LEFT JOIN users u ON o.user_id = u.id
LEFT JOIN bank_accounts b ON b.user_id = u.id
WHERE e.id = ?
LIMIT 1
");

if(!$stmt){
    echo json_encode(["error"=>"Failed load event"]);
    exit;
}

$stmt->bind_param("i", $event_id);
$stmt->execute();
$event = $stmt->get_result()->fetch_assoc();

if(!$event){
    echo json_encode(["error"=>"Event not found"]);
    exit;
}

/* ================= DUPLICATE CHECK ================= */
$check = $conn->prepare("
SELECT id
FROM event_registrations
WHERE user_id = ?
AND event_id = ?
AND status IN ('registered','attended')
LIMIT 1
");

$check->bind_param("ii", $user_id, $event_id);
$check->execute();

if($check->get_result()->num_rows > 0){
    echo json_encode(["error"=>"Already registered"]);
    exit;
}

/* ================= GET PARTICIPANT ================= */
$p = $conn->prepare("
SELECT id
FROM participants
WHERE user_id = ?
LIMIT 1
");

$p->bind_param("i", $user_id);
$p->execute();
$participant = $p->get_result()->fetch_assoc();

if(!$participant){
    echo json_encode(["error"=>"Participant profile not found"]);
    exit;
}

$participant_id = (int)$participant['id'];

/* ================= GET USER ================= */
$u = $conn->prepare("
SELECT 
    p.full_name,
    p.matric_no AS matric,
    p.staff_no,
    p.phone,
    u.email
FROM users u
LEFT JOIN participants p ON p.user_id = u.id
WHERE u.id = ?
LIMIT 1
");

$u->bind_param("i", $user_id);
$u->execute();
$user = $u->get_result()->fetch_assoc();

if(!$user){
    echo json_encode(["error"=>"User not found"]);
    exit;
}

$full_name = $user['full_name'] ?? '';
$matric    = $user['matric'] ?? '';
$phone     = $user['phone'] ?? '';
$email     = $user['email'] ?? '';

/* =====================================================
   FREE EVENT REGISTRATION
===================================================== */
if(strtolower($event['fee_type']) === "free"){

    $token = "EVT".strtoupper(substr(md5(uniqid()), 0, 10));

    $ins = $conn->prepare("
    INSERT INTO event_registrations
    (
        participant_id,
        event_id,
        user_id,
        token,
        payment_status,
        status,
        status_ticket
    )
    VALUES
    (?, ?, ?, ?, 'Free', 'registered', 'valid')
    ");

    if(!$ins){
        echo json_encode(["error"=>"Registration query failed"]);
        exit;
    }

    $ins->bind_param(
        "iiis",
        $participant_id,
        $event_id,
        $user_id,
        $token
    );

    if(!$ins->execute()){
        echo json_encode([
            "error"=>"Registration failed",
            "sql_error"=>$ins->error
        ]);
        exit;
    }

    /* ================= NOTIFICATION FIX ================= */
    notify(
        $conn,
        $user_id,
        "Event Registration Successful",
        "You have successfully registered for ".$event['title'],
        "registration",
        $event_id
    );

    /* ================= EMAIL ================= */
    try {
        sendRegistrationEmail(
            $email,
            $full_name,
            [
                "title"=>$event['title'],
                "event_date"=>$event['event_date'],
                "event_time"=>$event['start_time'],
                "venue"=>$event['venue'] ?? '-',
                "mode"=>$event['mode'],
                "meeting_link"=>$event['meeting_link'] ?? ''
            ],
            $token
        );
    } catch(Exception $e){
        error_log("Email Error: ".$e->getMessage());
    }

    echo json_encode([
        "type"=>"free",
        "title"=>$event['title'],
        "club"=>$event['club_name'],
        "mode"=>$event['mode'],
        "meeting_link"=>$event['meeting_link'] ?? '',
        "date"=>$event['event_date'],
        "time"=>$event['start_time'],
        "name"=>$full_name,
        "matric"=>$matric,
        "email"=>$email,
        "token"=>$token
    ]);

    exit;
}

/* =====================================================
   PAID EVENT RESPONSE
===================================================== */
echo json_encode([
    "type"=>"paid",
    "event_id"=>$event_id,
    "title"=>$event['title'],
    "club"=>$event['club_name'],
    "mode"=>$event['mode'],
    "meeting_link"=>$event['meeting_link'] ?? '',
    "amount"=>number_format((float)($event['fee_amount'] ?? 0), 2),
    "bank_holder"=>$event['account_holder_name'] ?? '-',
    "bank_name"=>$event['bank_name'] ?? '-',
    "bank_account_number"=>$event['account_number'] ?? '-'
]);

exit;
?>