<?php

session_start();

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

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

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


/* ======================================================
   FILTER
====================================================== */

$search =
mysqli_real_escape_string(
$conn,
$_GET['search'] ?? ""
);

$roleFilter =
mysqli_real_escape_string(
$conn,
$_GET['role'] ?? ""
);

$statusFilter =
mysqli_real_escape_string(
$conn,
$_GET['status'] ?? ""
);


/* ======================================================
   PAGINATION
====================================================== */

$limit = 10;

$page =
isset($_GET['page'])
? (int)$_GET['page']
: 1;

if($page < 1){
    $page = 1;
}

$offset =
($page - 1) * $limit;


/* ======================================================
   QUERY
====================================================== */

$sql = "

SELECT

u.id,
u.email,
u.role,
u.status,

/* PARTICIPANTS */
p.full_name,
p.phone,
p.matric_no,
p.staff_no,

/* ORGANIZER */
o.club_name,
o.advisor_name,
o.advisor_phone

FROM users u

LEFT JOIN participants p
ON p.user_id = u.id

LEFT JOIN organizers o
ON o.user_id = u.id

WHERE 1

";


/* ======================================================
   SEARCH
====================================================== */

if($search!=""){

$sql .= "
AND (

u.email LIKE '%$search%'
OR p.full_name LIKE '%$search%'
OR o.club_name LIKE '%$search%'

)
";
}


/* ======================================================
   ROLE FILTER
====================================================== */

if($roleFilter!=""){

$sql .= "
AND u.role='$roleFilter'
";
}


/* ======================================================
   STATUS FILTER
====================================================== */

if($statusFilter!=""){

$sql .= "
AND u.status='$statusFilter'
";
}


/* ======================================================
   TOTAL ROW
====================================================== */

$totalQuery =
mysqli_query($conn,$sql);

$totalRows =
mysqli_num_rows($totalQuery);

$totalPages =
ceil($totalRows / $limit);


/* ======================================================
   FINAL QUERY
====================================================== */

$sql .= "
ORDER BY u.id DESC
LIMIT $offset,$limit
";

$q = mysqli_query($conn,$sql);

$currentPage =
basename($_SERVER['PHP_SELF']);

?>

<link
rel="stylesheet"
href="/SEAT/assets/css/admin/userlist.css"
>

<div class="content">


    <!-- ==================================================
         TAB BAR
    =================================================== -->

    <div class="tabBar">

        <a
        href="userlist.php"
        class="<?= $currentPage=="userlist.php"
        ? "active"
        : "" ?>"
        >
        View Users
        </a>

        <a
        href="create_subAdmin.php"
        class="<?= $currentPage=="create_subAdmin.php"
        ? "active"
        : "" ?>"
        >
        Add Admin
        </a>

    </div>


    <!-- ==================================================
         PAGE TITLE
    =================================================== -->

    <h2 class="pageTitle">
        User List
    </h2>


    <!-- ==================================================
         BOX
    =================================================== -->

    <div class="box">

        <div class="boxHeader">

            <div>

                <div class="boxTitle">
                    All Users
                </div>

                <div class="boxSub">
                    Search / Filter / Manage users
                </div>

            </div>

        </div>


        <!-- ==================================================
             FILTER
        =================================================== -->

        <form
        method="get"
        class="filterBar"
        >

            <input
            type="text"
            name="search"
            placeholder="Search..."
            value="<?= htmlspecialchars($search) ?>"
            >

            <select name="role">

                <option value="">
                    All Role
                </option>

                <option
                value="student"
                <?= $roleFilter=="student"
                ? "selected"
                : "" ?>
                >
                Student
                </option>

                <option
                value="staff"
                <?= $roleFilter=="staff"
                ? "selected"
                : "" ?>
                >
                Staff
                </option>

                <option
                value="organizer"
                <?= $roleFilter=="organizer"
                ? "selected"
                : "" ?>
                >
                Organizer
                </option>

                <option
                value="admin"
                <?= $roleFilter=="admin"
                ? "selected"
                : "" ?>
                >
                Admin
                </option>

            </select>


            <select name="status">

                <option value="">
                    All Status
                </option>

                <option
                value="active"
                <?= $statusFilter=="active"
                ? "selected"
                : "" ?>
                >
                Active
                </option>

                <option
                value="inactive"
                <?= $statusFilter=="inactive"
                ? "selected"
                : "" ?>
                >
                Inactive
                </option>

                <option
                value="pending"
                <?= $statusFilter=="pending"
                ? "selected"
                : "" ?>
                >
                Pending
                </option>

            </select>


            <button class="btn btnBlue">
                Filter
            </button>

        </form>


        <!-- ==================================================
             TABLE
        =================================================== -->

        <div class="tableWrap">

        <table>

            <tr>

                <th>Bil</th>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>ID Number</th>
                <th>Role</th>
                <th>Status</th>

            </tr>

            <?php

            $bil = $offset + 1;

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

            ?>

            <tr>

                <!-- BIL -->

                <td>
                    <?= $bil++ ?>
                </td>


                <!-- NAME -->

                <td>

                    <?php

                    if(
                    $d['role']=="student"
                    ||
                    $d['role']=="staff"
                    ){

                        echo htmlspecialchars(
                            $d['full_name']
                        );

                    }

                    else if(
                    $d['role']=="organizer"
                    ){

                        echo htmlspecialchars(
                            $d['club_name']
                        );

                    }

                    else{

                        echo "Administrator";

                    }

                    ?>

                </td>


                <!-- EMAIL -->

                <td>

                    <?= htmlspecialchars(
                        $d['email']
                    ) ?>

                </td>


                <!-- PHONE -->

                <td>

                    <?php

                    if(
                    $d['role']=="student"
                    ||
                    $d['role']=="staff"
                    ){

                        echo htmlspecialchars(
                            $d['phone']
                        );

                    }

                    else if(
                    $d['role']=="organizer"
                    ){

                        $advisor =
                        htmlspecialchars(
                            $d['advisor_name']
                        );

                        $phone =
                        htmlspecialchars(
                            $d['advisor_phone']
                        );

                        echo "
                        <span
                        class='tooltip'
                        data-tip='Advisor: $advisor'
                        >
                        $phone
                        </span>
                        ";
                    }

                    else{

                        echo "-";

                    }

                    ?>

                </td>


                <!-- MATRIC / STAFF NO -->

                <td>

                    <?php

                    if(
                    $d['role']=="student"
                    &&
                    !empty($d['matric_no'])
                    ){

                        echo htmlspecialchars(
                            $d['matric_no']
                        );

                    }

                    else if(
                    $d['role']=="staff"
                    &&
                    !empty($d['staff_no'])
                    ){

                        echo htmlspecialchars(
                            $d['staff_no']
                        );

                    }

                    else{

                        echo "-";

                    }

                    ?>

                </td>


                <!-- ROLE -->

                <td>

                    <span class="badge roleBadge">

                        <?= ucfirst(
                            $d['role']
                        ) ?>

                    </span>

                </td>


                <!-- STATUS -->

                <td>

                    <span

                    class="badge statusBtn
                    <?= $d['status']=="active"
                    ? "activeBadge"
                    : "inactiveBadge" ?>"

                    onclick="changeStatus(
                    <?= $d['id'] ?>,
                    '<?= $d['status'] ?>'
                    )"

                    >

                    <?= ucfirst(
                        $d['status']
                    ) ?>

                    </span>

                </td>

            </tr>

            <?php } ?>

        </table>

        </div>


        <!-- ==================================================
             PAGINATION
        =================================================== -->

        <div class="pagination">

            <?php
            for($i=1; $i<=$totalPages; $i++){
            ?>

                <a

                href="?page=<?= $i ?>
                &search=<?= urlencode($search) ?>
                &role=<?= urlencode($roleFilter) ?>
                &status=<?= urlencode($statusFilter) ?>"

                class="<?= $page==$i
                ? "activePage"
                : "" ?>"

                >

                <?= $i ?>

                </a>

            <?php } ?>

        </div>

    </div>

</div>



<!-- ======================================================
     MODAL
====================================================== -->

<div id="modalBg" class="modalBg">

<div class="modalBox">

<div class="modalIcon">
⚙
</div>

<div class="modalTitle">
Change Account Status
</div>

<div class="modalText" id="modalText">
Confirm change?
</div>

<div class="modalBtns">

<button
class="btnCancel"
onclick="closeModal()"
>
Cancel
</button>

<button
class="btnConfirm"
onclick="confirmChange()"
>
Confirm
</button>

</div>

</div>

</div>



<script>

let userID = 0;
let newStatus = "";


/* ======================================================
   CHANGE STATUS
====================================================== */

function changeStatus(id,status){

userID = id;

newStatus =
status=="active"
? "inactive"
: "active";

document.getElementById(
"modalText"
).innerText =
"Change status to "
+ newStatus + " ?";

document.getElementById(
"modalBg"
).style.display="flex";

}


/* ======================================================
   CLOSE
====================================================== */

function closeModal(){

document.getElementById(
"modalBg"
).style.display="none";

}


/* ======================================================
   CONFIRM
====================================================== */

function confirmChange(){

fetch(
"toggle_user.php",
{

method:"POST",

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

body:
"id="+userID+
"&status="+newStatus

}

)

.then(r=>r.text())

.then(()=>{

location.reload();

});

}

</script>