<?php

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

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

/* =====================================================
GET ADMIN
===================================================== */

$query = mysqli_query($conn,"
SELECT 
    a.*,
    u.email
FROM admins a
LEFT JOIN users u
ON u.id = a.user_id
WHERE a.user_id = '$user_id'
LIMIT 1
");

$admin = mysqli_fetch_assoc($query);

if(!$admin){
    die("Admin profile not found");
}

?>

<!-- FONT AWESOME -->

<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"
/>

<div class="profileCard">

    <!-- BACKGROUND EFFECT -->

    <div class="profileGlow"></div>

    <!-- HEADER -->

    <div class="profileHeader">

        <div class="profileHeaderLeft">

            <!-- AVATAR -->

            <div class="profileAvatar">

                <i class="fa-solid fa-user-shield"></i>

            </div>

            <!-- TITLE -->

            <div>

                <h2 class="profileTitle">

                    Admin Profile

                </h2>

                <p class="profileSub">

                    Manage your administrator account information

                </p>

            </div>

        </div>

        <!-- ACTION BUTTON -->

        <div class="profileActions">

            <button
            type="button"
            id="editBtn"
            class="btnEdit">

                <i class="fa-solid fa-pen"></i>

                Edit

            </button>

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

                <i class="fa-solid fa-xmark"></i>

                Cancel

            </button>

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

                <i class="fa-solid fa-floppy-disk"></i>

                Save

            </button>

        </div>

    </div>


    <!-- PROFILE GRID -->

    <div class="profileGrid">

        <!-- FULL NAME -->

        <div class="profileItem">

            <div class="profileIcon blue">

                <i class="fa-solid fa-user"></i>

            </div>

            <div class="profileContent">

                <label>Full Name</label>

                <p>
                    <?= htmlspecialchars(
                        $admin['full_name'] ?? '-'
                    ) ?>
                </p>

            </div>

        </div>


        <!-- EMAIL -->

        <div class="profileItem">

            <div class="profileIcon purple">

                <i class="fa-solid fa-envelope"></i>

            </div>

            <div class="profileContent">

                <label>Email Address</label>

                <p>
                    <?= htmlspecialchars(
                        $admin['email'] ?? '-'
                    ) ?>
                </p>

            </div>

        </div>


        <!-- PHONE -->

        <div class="profileItem">

            <div class="profileIcon green">

                <i class="fa-solid fa-phone"></i>

            </div>

            <div class="profileContent">

                <label>Phone Number</label>

                <!-- DISPLAY -->

                <p id="phoneText">

                    <?= htmlspecialchars(
                        $admin['phone_number'] ?? '-'
                    ) ?>

                </p>

                <!-- INPUT -->

                <input
                type="text"
                id="phoneInput"
                class="editInput"
                value="<?= htmlspecialchars(
                    $admin['phone_number'] ?? ''
                ) ?>"
                style="display:none;"
                maxlength="11"
                autocomplete="off"
                placeholder="Enter phone number"
                >

                <small
                id="phoneError"
                class="inputError">
                </small>

            </div>

        </div>


        <!-- STATUS -->

        <div class="profileItem">

            <div class="profileIcon orange">

                <i class="fa-solid fa-circle-check"></i>

            </div>

            <div class="profileContent">

                <label>Account Status</label>

                <span class="statusBadge active">

                    <i class="fa-solid fa-check"></i>

                    ACTIVE

                </span>

            </div>

        </div>

    </div>

</div>


<!-- TOAST -->

<div id="toastBox"></div>


<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 phoneError = document.getElementById("phoneError");

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

let originalPhone = phoneInput.value.trim();


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

editBtn.addEventListener("click", function(){

    phoneText.style.display = "none";

    phoneInput.style.display = "block";

    phoneInput.focus();

    editBtn.style.display = "none";

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

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

});


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

cancelBtn.addEventListener("click", function(){

    phoneInput.value = originalPhone;

    phoneText.style.display = "block";

    phoneInput.style.display = "none";

    phoneError.innerText = "";

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

    cancelBtn.style.display = "none";

    saveBtn.style.display = "none";

});


/* =====================================================
LIVE VALIDATION
===================================================== */

phoneInput.addEventListener("input", function(){

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

    const phone =
    phoneInput.value.trim();

    phoneError.innerText = "";

    if(phone.length > 0){

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

            phoneError.innerText =
            "Phone must start with 01";

        }
        else if(
            phone.length < 10 ||
            phone.length > 11
        ){

            phoneError.innerText =
            "Phone must be 10-11 digits";
        }
    }

});


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

saveBtn.addEventListener("click", function(){

    const phone =
    phoneInput.value.trim();

    phoneError.innerText = "";

    /* EMPTY */

    if(!phone){

        phoneError.innerText =
        "Phone number is required";

        return;
    }

    /* FORMAT */

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

        phoneError.innerText =
        "Invalid phone number format";

        return;
    }

    /* NO CHANGE */

    if(phone === originalPhone){

        showToast(
            "No changes detected",
            "error"
        );

        return;
    }

    /* LOADING */

    saveBtn.disabled = true;

    saveBtn.innerHTML =
    '<i class="fa-solid fa-spinner fa-spin"></i> Saving';


    fetch("updateProfile.php", {

        method: "POST",

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

        body:
        "phone=" +
        encodeURIComponent(phone)

    })

    .then(res => res.json())

    .then(data => {

        showToast(
            data.message,
            data.status
        );

        if(data.status === "success"){

            originalPhone = phone;

            phoneText.innerText = phone;

            phoneText.style.display = "block";

            phoneInput.style.display = "none";

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

            cancelBtn.style.display = "none";

            saveBtn.style.display = "none";

            phoneError.innerText = "";
        }

    })

    .catch(error => {

        console.log(error);

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

    })

    .finally(() => {

        saveBtn.disabled = false;

        saveBtn.innerHTML =
        '<i class="fa-solid fa-floppy-disk"></i> Save';

    });

});


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

function showToast(message, type){

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

    toast.className =
    "toast " + type;

    toast.innerHTML = message;

    toastBox.appendChild(toast);

    setTimeout(() => {

        toast.style.opacity = "0";

        toast.style.transform =
        "translateX(100%)";

    }, 2500);

    setTimeout(() => {

        toast.remove();

    }, 3200);

}

</script>