<?php

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

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

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

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

/* ================= RESPONSE ================= */
function sendJSON($arr){
    ob_clean();
    echo json_encode($arr);
    exit;
}

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

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

/* ================= INPUT ================= */
$data = json_decode(file_get_contents("php://input"), true);

if(!$data){
    sendJSON(["error"=>"Invalid request"]);
}

$event_id = (int)($data['event_id'] ?? 0);
$method   = trim($data['payment_method'] ?? 'Card');

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

/* ================= EVENT ================= */
$stmt = $conn->prepare("
SELECT 
    e.*,
    o.club_name
FROM events e
LEFT JOIN organizers o ON e.organizer_id = o.id
WHERE e.id = ?
LIMIT 1
");

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

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

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

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

if($dup->get_result()->num_rows > 0){
    sendJSON(["error"=>"Already registered"]);
}

/* ================= USER (participants ONLY) ================= */
$u = $conn->prepare("
SELECT 
    p.full_name,
    p.matric_no,
    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){
    sendJSON(["error"=>"User not found"]);
}

/* ================= PARTICIPANT ID ================= */
$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){
    sendJSON(["error"=>"Participant profile not found"]);
}

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



/* ================= VALUES ================= */
$amount = (float)$event['fee_amount'];

$token = "EVT".strtoupper(substr(md5(uniqid(mt_rand(),true)),0,10));
$trx   = "TRX".date("YmdHis").rand(100,999);



/* ================= TRANSACTION ================= */
$conn->begin_transaction();

try{

    /* ================= REGISTRATION ================= */
    $reg = $conn->prepare("
    INSERT INTO event_registrations
    (
        participant_id,
        event_id,
        user_id,
        token,
        payment_status,
        status,
        status_ticket
    )
    VALUES
    (?, ?, ?, ?, 'Paid', 'registered', 'valid')
    ");

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

    if(!$reg->execute()){
        throw new Exception("Registration failed: ".$reg->error);
    }

    $registration_id = $conn->insert_id;

    /* ================= PAYMENT ================= */
    $pay = $conn->prepare("
    INSERT INTO payments
    (
        registration_id,
        event_id,
        user_id,
        amount,
        payment_method,
        transaction_id,
        payment_status,
        paid_at
    )
    VALUES
    (?, ?, ?, ?, ?, ?, 'Paid', NOW())
    ");

    $pay->bind_param(
        "iiidss",
        $registration_id,
        $event_id,
        $user_id,
        $amount,
        $method,
        $trx
    );

    if(!$pay->execute()){
        throw new Exception("Payment failed: ".$pay->error);
    }

    /* ================= NOTIFICATION  ================= */
        notify(
            $conn,
            $user_id,
            "Event Registration Successful",
            "You have successfully registered for " . ($event['title'] ?? 'this event'),
            "event",
            $event_id
        );
        
        $conn->commit();
        
        }catch(Exception $e){
        
            $conn->rollback();
        
            sendJSON([
                "error"   => "Registration failed",
                "details" => $e->getMessage()
            ]);
        }

/* ================= EMAIL ================= */
try{
    sendPaymentEmail(
        $user['email'],
        $user['full_name'],
        $event,
        $amount,
        $trx
    );
}catch(Exception $e){
    error_log("Payment Email Error: ".$e->getMessage());
}

try{
    sendRegistrationEmail(
        $user['email'],
        $user['full_name'],
        $event,
        $token
    );
}catch(Exception $e){
    error_log("Registration Email Error: ".$e->getMessage());
}

/* ================= RESPONSE ================= */
sendJSON([
    "success"=>true,
    "event_id"=>$event_id,
    "title"=>$event['title'],
    "club"=>$event['club_name'] ?? '',
    "amount"=>number_format($amount,2),
    "token"=>$token,
    "mode"=>$event['mode'] ?? '',
    "meeting_link"=>$event['meeting_link'] ?? '',
    "date"=>$event['event_date'] ?? '',
    "time"=>$event['start_time'] ?? '',
    "venue"=>$event['venue'] ?? '',
    "name"=>$user['full_name'] ?? '',
    "matric"=>$user['matric_no'] ?? $user['staff_no'] ?? '',
    "email"=>$user['email'] ?? ''
]);
?>