<?php
session_start();

header("Content-Type: application/json; charset=UTF-8");

include("../../../config/db.php");
require_once("../../../modules/Notification/notification_helper.php");

if (!isset($_SESSION['role']) || $_SESSION['role'] !== "organizer") {
    exit(json_encode([
        "status" => "error",
        "msg" => "No access"
    ]));
}

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

/* =====================================================
   ORGANIZER
===================================================== */
$q = mysqli_query($conn,"
    SELECT id, club_name
    FROM organizers
    WHERE user_id = $user_id
    LIMIT 1
");

$org = mysqli_fetch_assoc($q);

if(!$org){
    exit(json_encode([
        "status"=>"error",
        "msg"=>"Organizer not found"
    ]));
}

$organizer_id = (int)$org['id'];
$club_name    = $org['club_name'];

/* =====================================================
   HELPERS
===================================================== */
function res($status,$msg,$extra=[]){

    echo json_encode(array_merge([
        "status"=>$status,
        "msg"=>$msg
    ],$extra));

    exit;
}

function esc($conn,$v){
    return mysqli_real_escape_string($conn,trim($v));
}

function getEventInfo($conn,$id){

    $q = mysqli_query($conn,"
        SELECT title,event_date,start_time
        FROM events
        WHERE id=$id
        LIMIT 1
    ");

    return mysqli_fetch_assoc($q);
}

function uploadPoster($field="poster"){

    if(empty($_FILES[$field]['name'])){
        return "";
    }

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

    $allow = ["jpg","jpeg","png","webp"];

    if(!in_array($ext,$allow)){
        return false;
    }

    if($_FILES[$field]['size'] > 5 * 1024 * 1024){
        return false;
    }

    $dir = "../../../uploads/event_posters/";

    if(!is_dir($dir)){
        mkdir($dir,0777,true);
    }

    $name = time()."_".rand(1000,9999).".".$ext;

    if(move_uploaded_file($_FILES[$field]['tmp_name'],$dir.$name)){
        return $name;
    }

    return false;
}

/* =====================================================
   CHECK PARTICIPANT
===================================================== */
if(isset($_POST['check_participant'])){

    $id = (int)$_POST['event_id'];

    $q = mysqli_query($conn,"
        SELECT COUNT(*) total
        FROM event_registrations
        WHERE event_id = $id
    ");

    $r = mysqli_fetch_assoc($q);

    res("success","Checked",[
        "hasParticipant" => $r['total'] > 0
    ]);
}

/* =====================================================
   CREATE EVENT
===================================================== */
if(isset($_POST['create_event'])){

    $title = esc($conn,$_POST['title']);

    $date  = $_POST['event_date'];
    $start = $_POST['start_time'];
    $end   = $_POST['end_time'];

    $mode = $_POST['mode'];

    $venue   = esc($conn,$_POST['venue'] ?? '');
    $meeting = esc($conn,$_POST['meeting_link'] ?? '');

    $fee_type = $_POST['fee_type'];

    $fee = ($fee_type === "Paid")
        ? (float)$_POST['fee_amount']
        : 0;

    $max = (int)$_POST['max_participant'];

    if($title === ""){
        res("error","Title required");
    }

    if($end <= $start){
        res("error","End time invalid");
    }

    if($mode === "Physical" && $venue === ""){
        res("error","Venue required");
    }

    if($mode === "Online" && $meeting === ""){
        res("error","Meeting link required");
    }

    $poster = uploadPoster();

    if($poster === false){
        res("error","Invalid poster");
    }

    $poster_sql = $poster ? "'$poster'" : "NULL";

    $venue_sql = $mode === "Physical"
        ? "'$venue'"
        : "NULL";

    $meeting_sql = $mode === "Online"
        ? "'$meeting'"
        : "NULL";

    $q = mysqli_query($conn,"
        INSERT INTO events(
            organizer_id,
            title,
            event_date,
            start_time,
            end_time,
            mode,
            venue,
            meeting_link,
            fee_type,
            fee_amount,
            max_participant,
            poster,
            status
        )
        VALUES(
            $organizer_id,
            '$title',
            '$date',
            '$start',
            '$end',
            '$mode',
            $venue_sql,
            $meeting_sql,
            '$fee_type',
            '$fee',
            '$max',
            $poster_sql,
            'upcoming'
        )
    ");

    $q
        ? res("success","Event created")
        : res("error",mysqli_error($conn));
}

/* =====================================================
   EDIT EVENT + NOTIFY
===================================================== */
if(isset($_POST['edit_event'])){

    $id = (int)$_POST['event_id'];

    $title = esc($conn,$_POST['title']);

    $date  = $_POST['event_date'];
    $start = $_POST['start_time'];
    $end   = $_POST['end_time'];

    $mode = $_POST['mode'];

    $venue   = esc($conn,$_POST['venue'] ?? '');
    $meeting = esc($conn,$_POST['meeting_link'] ?? '');

 

    $fee_type = $_POST['fee_type'];
    
    $fee_amount_raw = $_POST['fee_amount'] ?? 0;
    
    if ($fee_type === "Paid") {
    
        if (!preg_match('/^\d+(\.\d{1,2})?$/', $fee_amount_raw)) {
            res("error", "Invalid amount (max 2 decimal places only)");
        }
    
        $fee = number_format((float)$fee_amount_raw, 2, '.', '');
    
    } else {
        $fee = 0;
}



    $max = (int)$_POST['max_participant'];

    $poster = uploadPoster();

    $poster_sql = $poster
        ? ", poster='$poster'"
        : "";

    $venue_sql = $mode === "Physical"
        ? "'$venue'"
        : "NULL";

    $meeting_sql = $mode === "Online"
        ? "'$meeting'"
        : "NULL";

    $q = mysqli_query($conn,"
        UPDATE events SET
            title='$title',
            event_date='$date',
            start_time='$start',
            end_time='$end',
            mode='$mode',
            venue=$venue_sql,
            meeting_link=$meeting_sql,
            fee_type='$fee_type',
            fee_amount='$fee',
            max_participant='$max'
            $poster_sql
        WHERE id=$id
        AND organizer_id=$organizer_id
    ");

    if($q){

        $event = getEventInfo($conn,$id);
        $eventTitle = $event['title'] ?? $title;

        $regs = mysqli_query($conn,"
            SELECT DISTINCT user_id
            FROM event_registrations
            WHERE event_id=$id
        ");

        while($r = mysqli_fetch_assoc($regs)){

            notify(
                $conn,
                $r['user_id'],
                "Event Update",
                "$eventTitle has updated event details",
                "event_update",
                $id
            );
        }

        res("success","Event updated");
    }

    res("error",mysqli_error($conn));
}

/* =====================================================
   POSTPONE EVENT + NOTIFY
===================================================== */
if(isset($_POST['postpone_event'])){

    $id = (int)$_POST['event_id'];

    $date  = $_POST['event_date'];
    $start = $_POST['start_time'];
    $end   = $_POST['end_time'];

    $q = mysqli_query($conn,"
        UPDATE events SET
            event_date='$date',
            start_time='$start',
            end_time='$end'
        WHERE id=$id
        AND organizer_id=$organizer_id
    ");

    if($q){

        $event = getEventInfo($conn,$id);
        $title = $event['title'] ?? "Event";

        $msg = "$title has been postponed to $date at $start";

        $regs = mysqli_query($conn,"
            SELECT DISTINCT user_id
            FROM event_registrations
            WHERE event_id=$id
        ");

        while($r = mysqli_fetch_assoc($regs)){

            notify(
                $conn,
                $r['user_id'],
                "Event Postponed",
                $msg,
                "event_postpone",
                $id
            );
        }

        res("success","Schedule updated");
    }

    res("error",mysqli_error($conn));
}

/* =====================================================
   DELETE / CANCEL EVENT
===================================================== */
if(isset($_POST['delete_event'])){

    $id   = (int)$_POST['event_id'];
    $mode = $_POST['mode'];

    $event = getEventInfo($conn,$id);
    $title = $event['title'] ?? "Event";

    if($mode === "cancel"){

        $q = mysqli_query($conn,"
            UPDATE events SET
                status='cancelled'
            WHERE id=$id
            AND organizer_id=$organizer_id
        ");

        if($q){

            $msg = "$title has been cancelled";

            $regs = mysqli_query($conn,"
                SELECT DISTINCT user_id
                FROM event_registrations
                WHERE event_id=$id
            ");

            while($r = mysqli_fetch_assoc($regs)){

                notify(
                    $conn,
                    $r['user_id'],
                    "Event Cancelled",
                    $msg,
                    "event_cancel",
                    $id
                );
            }

            res("success","Event cancelled");
        }
    }

    $q = mysqli_query($conn,"
        DELETE FROM events
        WHERE id=$id
        AND organizer_id=$organizer_id
    ");

    if($q){

        $msg = "$title has been removed by organizer";

        $regs = mysqli_query($conn,"
            SELECT DISTINCT user_id
            FROM event_registrations
            WHERE event_id=$id
        ");

        while($r = mysqli_fetch_assoc($regs)){

            notify(
                $conn,
                $r['user_id'],
                "Event Deleted",
                $msg,
                "event_delete",
                $id
            );
        }

        res("success","Event deleted");
    }

    res("error",mysqli_error($conn));
}

/* =====================================================
   SEND MESSAGE
===================================================== */
if(isset($_POST['send_message'])){

    $event_id = (int)$_POST['event_id'];
    $msg      = trim($_POST['message'] ?? '');

    $attachment = null;
    $file_type  = null;

    /* FILE UPLOAD */
    if(isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0){

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

        $allow = [
            "jpg","jpeg","png","webp",
            "pdf","doc","docx"
        ];

        if(in_array($ext,$allow)){

            $dir = "../../../uploads/event_messages/";

            if(!is_dir($dir)){
                mkdir($dir,0777,true);
            }

            $name = time().rand(1000,9999).".".$ext;

            if(move_uploaded_file(
                $_FILES['attachment']['tmp_name'],
                $dir.$name
            )){
                $attachment = $name;
                $file_type  = $ext;
            }
        }
    }

    if($msg === "" && !$attachment){
        res("error","Message required");
    }

    $stmt = $conn->prepare("
        INSERT INTO event_messages(
            event_id,
            sender_id,
            message,
            attachment,
            file_type,
            created_at
        )
        VALUES(?,?,?,?,?,NOW())
    ");

    $stmt->bind_param(
        "iisss",
        $event_id,
        $user_id,
        $msg,
        $attachment,
        $file_type
    );

    if($stmt->execute()){

        $event = getEventInfo($conn,$event_id);
        $eventTitle = $event['title'] ?? "Event";

        $regs = mysqli_query($conn,"
            SELECT DISTINCT user_id
            FROM event_registrations
            WHERE event_id=$event_id
        ");

        while($r = mysqli_fetch_assoc($regs)){

            if((int)$r['user_id'] !== $user_id){

                notify(
                    $conn,
                    $r['user_id'],
                    "New Announcement",
                    "$club_name posted a new message for $eventTitle",
                    "event_message",
                    $event_id
                );
            }
        }

        res("success","Message sent");
    }

    res("error",$stmt->error);
}

/* =====================================================
   LOAD MESSAGES
===================================================== */
if(isset($_POST['load_messages'])){

    $event_id = (int)($_POST['event_id'] ?? 0);

    $check = mysqli_query($conn,"
        SELECT id
        FROM events
        WHERE id=$event_id
        AND organizer_id=$organizer_id
        LIMIT 1
    ");

    if(mysqli_num_rows($check) == 0){
        res("error","No access");
    }

    $q = mysqli_query($conn,"
        SELECT *
        FROM event_messages
        WHERE event_id=$event_id
        ORDER BY id DESC
    ");

    if(!$q){
        res("error","Failed to load messages");
    }

    $messages = [];

    while($m = mysqli_fetch_assoc($q)){

        $imageUrl = "";
        $fileUrl  = "";

        if(!empty($m['attachment'])){

            $path = "/SEAT/uploads/event_messages/".$m['attachment'];

            $imgExt = ["jpg","jpeg","png","webp"];

            if(in_array(strtolower($m['file_type']),$imgExt)){
                $imageUrl = $path;
            }else{
                $fileUrl = $path;
            }
        }

        $messages[] = [
            "id" => (int)$m['id'],
            "message" => nl2br(htmlspecialchars($m['message'])),
            "raw" => htmlspecialchars($m['message'], ENT_QUOTES),
            "image" => $imageUrl,
            "file" => $fileUrl,
            "created_at" => date(
                "d M Y h:i A",
                strtotime($m['created_at'])
            )
        ];
    }

    res("success","Loaded",[
        "messages"=>$messages
    ]);
}

/* =====================================================
   DELETE MESSAGE
===================================================== */
if(isset($_POST['delete_message'])){

    $id = (int)$_POST['message_id'];

    $check = mysqli_query($conn,"
        SELECT em.id
        FROM event_messages em
        INNER JOIN events e ON e.id = em.event_id
        WHERE em.id = $id
        AND e.organizer_id = $organizer_id
        LIMIT 1
    ");

    if(mysqli_num_rows($check) == 0){
        res("error","No access");
    }

    $q = mysqli_query($conn,"
        DELETE FROM event_messages
        WHERE id = $id
    ");

    if($q){
        res("success","Deleted");
    }

    res("error",mysqli_error($conn));
}

/* =====================================================
   FALLBACK
===================================================== */
res("error","Invalid request");
?>