<?php

session_start();

if(!isset($_SESSION['id'])){
    die("No access");
}

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

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

/* ================= FETCH USER  ================= */

$stmt = $conn->prepare("
SELECT 
    u.email,
    u.status,
    u.created_at,
    p.full_name,
    p.matric_no,
    p.staff_no,
    p.faculty,
    p.phone
FROM users u
JOIN participants p 
    ON p.user_id = u.id
WHERE u.id = ?
");

if(!$stmt){
    die("Query Error: " . $conn->error);
}

$stmt->bind_param("i",$user_id);
$stmt->execute();

$user = $stmt->get_result()->fetch_assoc();

if(!$user){
    die("User not found");
}

/* ================= UPCOMING EVENTS ================= */

$upcoming_stmt = $conn->prepare("
SELECT 
    e.id,
    e.title,
    e.event_date,
    e.start_time,
    e.end_time,
    e.venue,
    e.mode,
    e.poster
FROM event_registrations er
JOIN events e
    ON e.id = er.event_id
JOIN participants p
    ON p.id = er.participant_id
WHERE p.user_id = ?
AND er.status IN ('registered','attended')
AND e.event_date BETWEEN CURDATE()
AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
ORDER BY e.event_date ASC,
         e.start_time ASC
LIMIT 5
");

if(!$upcoming_stmt){
    die("Upcoming Query Error: " . $conn->error);
}

$upcoming_stmt->bind_param("i",$user_id);
$upcoming_stmt->execute();

$upcoming_events = $upcoming_stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">

<title>Participant Profile</title>

<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/participant/dashboard.css">

</head>
<body>

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

<div class="main">
<!-- ================= PROFILE ================= -->

<div class="card profileCard">

    <div class="cardHead">

        <h3>Participant 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">

        <!-- NAME -->
        <div class="infoItem">

            <div class="icon blue">
                <i class="fa fa-user"></i>
            </div>

            <div>
                <label>Full Name</label>
                <p><?= htmlspecialchars($user['full_name']) ?></p>
            </div>

        </div>

        <!-- MATRIC / STAFF -->
        <div class="infoItem">

            <div class="icon purple">
                <i class="fa fa-id-card"></i>
            </div>

            <div>
                <label>
                    <?= ($role === "student") ? "Matric No" : "Staff No" ?>
                </label>

                <p>
                    <?= htmlspecialchars($user['matric_no'] ?? $user['staff_no']) ?>
                </p>
            </div>

        </div>

        <!-- FACULTY (ONLY STUDENT) -->
        <?php if($role === 'student'): ?>

        <div class="infoItem">

            <div class="icon orange">
                <i class="fa fa-building"></i>
            </div>

            <div>
                <label>Faculty</label>
                <p><?= htmlspecialchars($user['faculty']) ?></p>
            </div>

        </div>

        <?php endif; ?>

        <!-- EMAIL -->
        <div class="infoItem">

            <div class="icon green">
                <i class="fa fa-envelope"></i>
            </div>

            <div>
                <label>Email</label>
                <p><?= htmlspecialchars($user['email']) ?></p>
            </div>

        </div>
        

        <!-- PHONE -->
        <div class="infoItem">

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

            <div>

                <label>Phone</label>

                <p id="phoneText">
                    <?= htmlspecialchars($user['phone']) ?>
                </p>

                <input
                type="text"
                id="phoneInput"
                value="<?= htmlspecialchars($user['phone']) ?>"
                class="editField"
                style="display:none;"
                maxlength="11"
                pattern="01[0-9]{8,9}"
                placeholder="0123456789"
                autocomplete="off"
                oninput="validatePhone()">

                <small id="phoneMsg"></small>

            </div>

        </div>

      <!-- REGISTER DATE -->
        <div class="infoItem">

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

            <div>
                <label>Registered</label>
                <p><?= date("d M Y", strtotime($user['created_at'])) ?></p>
            </div>

        </div>

        <!-- STATUS -->
        <div class="infoItem">

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

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

        </div>

    </div>

</div>

<!-- ================= UPCOMING EVENTS ================= -->

<div class="upcomingSection">

    <h2 class="sectionTitle">
        Upcoming Events This Week
    </h2>

    <?php if($upcoming_events->num_rows > 0): ?>

    <div class="upcomingWrapper">

        <?php while($event = $upcoming_events->fetch_assoc()): ?>

        <div class="eventRow">

            <div class="eventDate">

                <div class="dateDay">
                    <?= date("d", strtotime($event['event_date'])) ?>
                </div>

                <div class="dateMonth">
                    <?= strtoupper(date("M", strtotime($event['event_date']))) ?>
                </div>

            </div>

            <div class="eventBody">

                <h3 class="eventTitle">
                    <?= htmlspecialchars($event['title']) ?>
                </h3>

                <div class="eventMeta">

                    <div class="metaItem">
                        <i class="fa-solid fa-clock"></i>
                        <?= date("h:i A", strtotime($event['start_time'])) ?>
                        -
                        <?= date("h:i A", strtotime($event['end_time'])) ?>
                    </div>

                    <div class="metaItem">
                        <i class="fa-solid fa-location-dot"></i>
                        <?= htmlspecialchars($event['venue']) ?>
                    </div>

                    <div class="metaItem">
                        <i class="fa-solid fa-bolt"></i>
                        <?= htmlspecialchars($event['mode']) ?>
                    </div>

                </div>

            </div>

        </div>

        <?php endwhile; ?>

    </div>

    <?php else: ?>

    <div class="emptyUpcoming">
        <i class="fa-regular fa-calendar-xmark"></i>
        <p>No upcoming events</p>
    </div>

    <?php endif; ?>

</div>

</div>
<!-- ================= TOAST NOTIFICATION ================= -->
<div id="toast" class="toast"></div>
</body>
</html>




<script>

const editBtn =
document.getElementById("editBtn");

const cancelBtn =
document.getElementById("cancelBtn");

const saveBtn =
document.getElementById("saveBtn");

const phoneText =
document.getElementById("phoneText");

const phoneInput =
document.getElementById("phoneInput");

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

const toast =
document.getElementById("toast");

let phoneValid = true;

let saving = false;

/* =========================================================
TOAST
========================================================= */

function showToast(
    message,
    type = "success"
){

    toast.innerText = message;

    toast.className =
    "toast show " + type;

    setTimeout(() => {

        toast.className = "toast";

    },2500);
}

/* =========================================================
MESSAGE
========================================================= */

function setMsg(text,color){

    phoneMsg.innerText = text;

    phoneMsg.style.color = color;
}

/* =========================================================
EDIT
========================================================= */

editBtn.onclick = () => {

    phoneText.style.display =
    "none";

    phoneInput.style.display =
    "block";

    editBtn.style.display =
    "none";

    cancelBtn.style.display =
    "inline-block";

    saveBtn.style.display =
    "inline-block";

    validatePhone();
};

/* =========================================================
CANCEL
========================================================= */

cancelBtn.onclick = () => {

    phoneInput.value =
    phoneText.innerText
    .replace(/\D/g,'');

    phoneText.style.display =
    "block";

    phoneInput.style.display =
    "none";

    phoneMsg.innerText = "";

    editBtn.style.display =
    "inline-block";

    cancelBtn.style.display =
    "none";

    saveBtn.style.display =
    "none";
};

/* =========================================================
VALIDATE PHONE
========================================================= */

function validatePhone(){

    let value =
    phoneInput.value
    .replace(/\D/g,'')
    .slice(0,11);

    phoneInput.value = value;

    /* MUST START 01 */

    if(!value.startsWith("01")){

        setMsg(
            "Must start with 01",
            "red"
        );

        phoneValid = false;

        return;
    }

    /* LENGTH */

    if(value.length < 10){

        setMsg(
            "Must be 10–11 digits",
            "red"
        );

        phoneValid = false;

        return;
    }

    /* FORMAT */

    if(
        !/^01[0-9]{8,9}$/.test(value)
    ){

        setMsg(
            "Invalid format",
            "red"
        );

        phoneValid = false;

        return;
    }

    /* VALID */

    setMsg(
        "Valid ✓",
        "green"
    );

    phoneValid = true;
}

/* =========================================================
INPUT EVENT
========================================================= */

phoneInput.addEventListener(
"input",
validatePhone
);

/* =========================================================
SAVE
========================================================= */

saveBtn.onclick = () => {

    if(saving){
        return;
    }

    validatePhone();

    if(!phoneValid){

        showToast(
            "Fix phone number first",
            "error"
        );

        return;
    }

    let phone =
    phoneInput.value
    .replace(/\D/g,'');

    saving = true;

    saveBtn.disabled = true;

    saveBtn.innerHTML =
    "Updating...";

    fetch(
        "update_profile.php",
        {
            method:"POST",

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

            body:
            "phone=" +
            encodeURIComponent(phone)
        }
    )

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

    .then(res => {

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

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

            return;
        }

        /* UPDATE UI */

        phoneText.innerText =
        phone;

        phoneText.style.display =
        "block";

        phoneInput.style.display =
        "none";

        cancelBtn.style.display =
        "none";

        saveBtn.style.display =
        "none";

        editBtn.style.display =
        "inline-block";

        phoneMsg.innerText = "";

        showToast(
            res.message,
            "success"
        );

        /* OPTIONAL */

        if(
            typeof loadNotificationRealtime
            === "function"
        ){

            loadNotificationRealtime();
        }

    })

    .catch(error => {

        console.log(error);

        showToast(
            "Server error. Try again.",
            "error"
        );

    })

    .finally(() => {

        saving = false;

        saveBtn.disabled = false;

        saveBtn.innerHTML =
        "Update";

    });
};

</script>



