<?php
session_start();

// Only allow organizer
if (!isset($_SESSION['role']) || $_SESSION['role'] != "organizer") {
    die("No access");
}

include("../../../config/db.php");

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

/* ================= FETCH ORGANIZER DATA ================= */
$q = mysqli_query($conn, "
    SELECT 
        u.email, u.status, u.created_at,
        o.id AS organizer_id, o.club_name, o.advisor_name, o.advisor_phone, o.description
    FROM users u
    JOIN organizers o ON o.user_id = u.id
    WHERE u.id = $user_id
");

$org = mysqli_fetch_assoc($q);
if (!$org) {
    die("Organizer data not found");
}
$organizer_id = (int)$org['organizer_id'];

/* ================= FETCH UPCOMING EVENTS ================= */
$events = mysqli_query($conn, "
    SELECT id, title, event_date, start_time, end_time, venue, mode, max_participant
    FROM events
    WHERE organizer_id = $organizer_id
    AND event_date >= CURDATE()
    ORDER BY event_date ASC
    LIMIT 4
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Organizer Dashboard</title>

    <!-- CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="stylesheet" href="/SEAT/assets/css/organizer/layout.css">
    <link rel="stylesheet" href="/SEAT/assets/css/organizer/dashboard.css">
</head>
<body>

<?php 
include("../../../templates/header.php");
include("../../../templates/sidebar.php");

?>

<div class="main-content">
    <h1>Welcome, <?= htmlspecialchars($_SESSION['role']) ?></h1>
</div>

<div class="main">
    <h2>Overview</h2>
    <p class="sub">Welcome back, <b><?= htmlspecialchars($org['club_name']) ?></b></p>

    <!-- Association Profile -->


   <div class="card profileCard">

    <div class="cardHead">

        <h3>Association Profile</h3>

        <div class="actionBtns">

            <button id="editBtn" class="btnEdit">
                <i class="fa fa-pen"></i> Edit
            </button>

            <button id="cancelBtn" class="btnCancel" style="display:none;">
                Cancel
            </button>

            <button id="saveBtn" class="btnSave" style="display:none;">
                Update
            </button>

        </div>

    </div>


    <div class="infoGrid">

        <div class="infoItem">
            <div class="icon blue"><i class="fa fa-user"></i></div>
            <div>
                <label>Association Name</label>
                <p><?= htmlspecialchars($org['club_name']) ?></p>
            </div>
        </div>


        <div class="infoItem">
            <div class="icon green"><i class="fa fa-envelope"></i></div>
            <div>
                <label>Email</label>
                <p><?= htmlspecialchars($org['email']) ?></p>
            </div>
        </div>


        <div class="infoItem">
            <div class="icon purple"><i class="fa fa-calendar"></i></div>
            <div>
                <label>Registration Date</label>
                <p><?= date("d M Y", strtotime($org['created_at'])) ?></p>
            </div>
        </div>


        <!-- editable -->
        <div class="infoItem">
            <div class="icon orange"><i class="fa fa-user-tie"></i></div>

            <div>
                <label>Advisor Name</label>

                <p id="advisorNameText">
                    <?= htmlspecialchars($org['advisor_name']) ?>
                </p>

                <input 
                    type="text"
                    id="advisorName"
                    value="<?= htmlspecialchars($org['advisor_name']) ?>"
                    class="editField"
                >
            </div>
        </div>


        <!-- editable -->
        <div class="infoItem">
            <div class="icon pink"><i class="fa fa-phone"></i></div>

            <div>
                <label>Advisor Phone</label>
                <p id="advisorPhoneText" data-value="<?= htmlspecialchars($org['advisor_phone']) ?>">
                    <?= htmlspecialchars($org['advisor_phone']) ?>
                </p>
                             
                <input 
                    type="text"
                    id="advisorPhone"
                    value="<?= htmlspecialchars($org['advisor_phone']) ?>"
                    maxlength="11"
                    inputmode="numeric"
                    class="editField"
                    oninput="this.value = this.value.replace(/[^0-9]/g,'')">
                    <small id="advisorPhoneMsg" style="font-size:12px;"></small>
                
              </div>
        </div>


        <div class="infoItem">
            <div class="icon teal"><i class="fa fa-check"></i></div>

            <div>
                <label>Status</label>
                <span class="badge active">
                    <?= strtoupper($org['status']) ?>
                </span>
            </div>
        </div>

    </div>


<div class="descBox">

    <label>Description</label>

    <!-- display text -->
    <p id="descText">
        <?= nl2br(htmlspecialchars($org['description'])) ?>
    </p>

    <!-- edit textarea -->
    <textarea 
        id="descInput"
        class="editField"
        rows="4"
    ><?= htmlspecialchars($org['description']) ?></textarea>

</div>









</div>

    <!-- Upcoming Events -->
    <h3 class="mt">Upcoming Events</h3>
    <div class="eventList">
        <?php while($e = mysqli_fetch_assoc($events)): 
            $reg_res = mysqli_query($conn, "SELECT id FROM event_registrations WHERE event_id=".(int)$e['id']);
            $r = mysqli_num_rows($reg_res);
            $max = $e['max_participant'] > 0 ? $e['max_participant'] : 1;
            $percent = min(100, ($r / $max) * 100);
        ?>
        <div class="eventRow">
            <div class="dateBlock">
                <span class="day"><?= date("d", strtotime($e['event_date'])) ?></span>
                <span class="month"><?= date("M", strtotime($e['event_date'])) ?></span>
            </div>

            <div class="mainInfo">
                <h4><?= htmlspecialchars($e['title']) ?></h4>
                <div class="subDetails">
                    <span><i class="fa fa-clock"></i> <?= date("h:i A", strtotime($e['start_time'])) ?></span>
                    <span><i class="fa fa-location-dot"></i> <?= htmlspecialchars($e['venue']) ?></span>
                    <span><i class="fa fa-bolt"></i> <?= strtoupper($e['mode']) ?></span>
                </div>
            </div>

            
              
                <div class="progressMini">
                    <div style="display:flex; justify-content:space-between; font-size:12px; color:#475569;">
                        <span>Register: <?= $r ?>/<?= $e['max_participant'] ?></span>
                    </div>
                    <div class="barBg">
                        <div class="barFill" style="width:<?= $percent ?>%;"></div>
                    </div>
                </div>
            
        </div>
        <?php endwhile; ?>
    </div>
</div>


<!-- TOAST -->
<div id="toastWrap"></div>



<script>
/* ================= BASIC ================= */
const editBtn = document.getElementById("editBtn");
const cancelBtn = document.getElementById("cancelBtn");
const saveBtn = document.getElementById("saveBtn");

const nameText = document.getElementById("advisorNameText");
const phoneText = document.getElementById("advisorPhoneText");
const descText = document.getElementById("descText");

const nameInput = document.getElementById("advisorName");
const phoneInput = document.getElementById("advisorPhone");
const descInput = document.getElementById("descInput");

const phoneMsg = document.getElementById("advisorPhoneMsg");

/* ================= STORE ORIGINAL ================= */
nameText.dataset.value = nameText.textContent.trim();
phoneText.dataset.value = phoneText.dataset.value || phoneText.textContent.trim();
descText.dataset.value = descInput.value.trim();

/* ================= TOAST ================= */
function showToast(message,type="success"){

    const toast = document.createElement("div");

    toast.className = "toast " + type;

    toast.innerHTML = `
        <i class="fa ${type === 'success' ? 'fa-circle-check' : 'fa-circle-xmark'}"></i>
        <span>${message}</span>
    `;

    document.getElementById("toastWrap").appendChild(toast);

    setTimeout(()=>{
        toast.style.opacity = "0";
        toast.style.transform = "translateX(40px)";

        setTimeout(()=>{
            toast.remove();
        },300);

    },3000);
}

/* ================= UTIL ================= */
function setMsg(el, text, color){
    el.textContent = text;
    el.style.color = color;
}

function setBtnState(valid){
    saveBtn.disabled = !valid;
    saveBtn.style.opacity = valid ? "1" : "0.5";
    saveBtn.style.cursor = valid ? "pointer" : "not-allowed";
}

/* ================= CLEAN INPUT ================= */
function cleanPhone(val){
    return val.replace(/\D/g,'');
}

/* ================= CHECK DUPLICATE ================= */
function checkPhoneExists(value){

    return fetch("/SEAT/modules/User/auth/check_live.php", {
        method: "POST",
        headers: {
            "Content-Type":"application/x-www-form-urlencoded"
        },
        body: "field=advisor_phone&value=" + encodeURIComponent(value)
    })
    .then(res => res.json());
}

/* ================= VALIDATE PHONE ================= */
async function validateAdvisorPhone(){

    let value = cleanPhone(phoneInput.value);

    phoneInput.value = value;

    if(!value){

        setMsg(phoneMsg,"Required","red");
        setBtnState(false);
        return false;
    }

    if(!/^01\d{8,9}$/.test(value)){

        setMsg(phoneMsg,"Invalid format (01XXXXXXXXX)","red");
        setBtnState(false);
        return false;
    }

    let original = phoneText.dataset.value;

    if(value === original){

        setMsg(phoneMsg,"No changes","orange");
        setBtnState(true);
        return true;
    }

    setMsg(phoneMsg,"Checking...","gray");

    try{

        let res = await checkPhoneExists(value);

        if(res.exists){

            setMsg(phoneMsg,"Phone already exists","red");
            setBtnState(false);
            return false;
        }

        setMsg(phoneMsg,"Valid ✓","green");
        setBtnState(true);

        return true;

    }catch(err){

        setMsg(phoneMsg,"Validation failed","red");
        setBtnState(false);

        return false;
    }
}

/* ================= DEBOUNCE ================= */
let timer;

phoneInput.addEventListener("input", ()=>{

    clearTimeout(timer);

    timer = setTimeout(()=>{
        validateAdvisorPhone();
    },400);

});

/* ================= EDIT ================= */
editBtn.onclick = () => {

    nameInput.value = nameText.dataset.value;
    phoneInput.value = phoneText.dataset.value;
    descInput.value = descText.dataset.value;

    nameText.style.display = "none";
    phoneText.style.display = "none";
    descText.style.display = "none";

    nameInput.style.display = "block";
    phoneInput.style.display = "block";
    descInput.style.display = "block";

    editBtn.style.display = "none";
    cancelBtn.style.display = "inline-block";
    saveBtn.style.display = "inline-block";

    setBtnState(true);
};

/* ================= CANCEL ================= */
cancelBtn.onclick = () => {

    nameInput.value = nameText.dataset.value;
    phoneInput.value = phoneText.dataset.value;
    descInput.value = descText.dataset.value;

    nameText.style.display = "block";
    phoneText.style.display = "block";
    descText.style.display = "block";

    nameInput.style.display = "none";
    phoneInput.style.display = "none";
    descInput.style.display = "none";

    cancelBtn.style.display = "none";
    saveBtn.style.display = "none";
    editBtn.style.display = "inline-block";

    phoneMsg.textContent = "";
};

/* ================= SAVE ================= */
saveBtn.onclick = async () => {

    const name = nameInput.value.trim();
    const phone = cleanPhone(phoneInput.value);
    const desc = descInput.value.trim();

    if (!name || !phone || !desc) {

        showToast("All fields are required","error");
        return;
    }

    let valid = await validateAdvisorPhone();

    if(!valid){

        showToast("Fix advisor phone first","error");
        return;
    }

    /* loading state */
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Updating...';

    fetch("editProfile.php", {

        method: "POST",

        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },

        body:
            "advisor_name=" + encodeURIComponent(name) +
            "&advisor_phone=" + encodeURIComponent(phone) +
            "&description=" + encodeURIComponent(desc)

    })
    .then(r => r.json())

    .then(res => {

        if(res.status !== "success"){

            showToast(res.message || "Update failed","error");

            saveBtn.disabled = false;
            saveBtn.innerHTML = 'Update';

            return;
        }

        /* update text */
        nameText.textContent = name;
        phoneText.textContent = phone;
        descText.innerHTML = desc.replace(/\n/g,"<br>");

        /* update stored */
        nameText.dataset.value = name;
        phoneText.dataset.value = phone;
        descText.dataset.value = desc;

        /* switch back */
        nameText.style.display = "block";
        phoneText.style.display = "block";
        descText.style.display = "block";

        nameInput.style.display = "none";
        phoneInput.style.display = "none";
        descInput.style.display = "none";

        cancelBtn.style.display = "none";
        saveBtn.style.display = "none";
        editBtn.style.display = "inline-block";

        phoneMsg.textContent = "";

        saveBtn.disabled = false;
        saveBtn.innerHTML = 'Update';

        showToast("Profile updated successfully","success");

    })

    .catch(() => {

        showToast("Server error occurred","error");

        saveBtn.disabled = false;
        saveBtn.innerHTML = 'Update';

    });

};
</script>
</body>
</html>