<?php

session_start();

error_reporting(E_ALL);
ini_set('display_errors',1);

define("ROOT", $_SERVER['DOCUMENT_ROOT']."/SEAT");

include(ROOT."/config/db.php");
include("../../../templates/header.php");
include("../../../templates/sidebar.php");


/* =========================
   ACCESS CHECK
========================= */

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




/* =========================
   CURRENT PAGE
========================= */

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

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

$msg  = "";
$type = "";

/* =========================
   RANDOM PASSWORD
========================= */

function generatePassword($length = 7){

    $uppercase = "ABCDEFGHJKLMNPQRSTUVWXYZ";
    $lowercase = "abcdefghijkmnopqrstuvwxyz";
    $numbers   = "23456789";
    $symbols   = "@#$%&";

    $password =

        $uppercase[rand(0, strlen($uppercase)-1)] .
        $lowercase[rand(0, strlen($lowercase)-1)] .
        $numbers[rand(0, strlen($numbers)-1)] .
        $symbols[rand(0, strlen($symbols)-1)];

    $all =
    $uppercase.$lowercase.$numbers.$symbols;

    while(strlen($password) < $length){

        $password .=
        $all[rand(0, strlen($all)-1)];
    }

    return str_shuffle($password);
}

/* =========================
   ADD ADMIN
========================= */

if(isset($_POST['add_subadmin'])){

    $full_name =
    trim($_POST['full_name'] ?? "");

    $phone =
    trim($_POST['phone_number'] ?? "");

    $email =
    trim($_POST['email'] ?? "");

    $errors = [];

    $email =
    strtolower($email);

    $phone =
    preg_replace('/[^0-9]/','',$phone);

    $full_name =
    mysqli_real_escape_string(
    $conn,
    $full_name
    );

    $email =
    mysqli_real_escape_string(
    $conn,
    $email
    );

    $phone =
    mysqli_real_escape_string(
    $conn,
    $phone
    );

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

    if(
    empty($full_name)
    ||
    empty($phone)
    ||
    empty($email)
    ){
        $errors[] =
        "Please fill all fields";
    }

    /* EMAIL */

    if(!preg_match(
    '/^[a-zA-Z0-9._%+-]+@usm\.my$/',
    $email
    )){
        $errors[] =
        "Admin email must use @usm.my";
    }

    /* PHONE */

    if(!preg_match(
    '/^01[0-9]{8,9}$/',
    $phone
    )){
        $errors[] =
        "Invalid phone number";
    }

    /* DUPLICATE */

    $check =
    mysqli_query(
    $conn,
    "SELECT id
    FROM users
    WHERE email='$email'"
    );

    if(mysqli_num_rows($check)>0){

        $errors[] =
        "Email already exists";
    }

    /* ================= INSERT ================= */

    if(empty($errors)){

        $generatedPassword =
        generatePassword(7);

        $hashed =
        password_hash(
        $generatedPassword,
        PASSWORD_DEFAULT
        );

        mysqli_query($conn,"
        INSERT INTO users
        (
            email,
            password,
            role,
            status
        )
        VALUES
        (
            '$email',
            '$hashed',
            'admin',
            'active'
        )
        ");

        $user_id =
        mysqli_insert_id($conn);

        mysqli_query($conn,"
        INSERT INTO admins
        (
            user_id,
            full_name,
            phone_number
        )
        VALUES
        (
            '$user_id',
            '$full_name',
            '$phone'
        )
        ");

        $msg =
        "Admin created successfully.<br>
        Generated Password:
        <b>$generatedPassword</b>";

        $type = "success";

    }else{

        $msg =
        implode("<br>",$errors);

        $type = "error";
    }
}

/* =========================
   GET ADMINS
========================= */

$admins = mysqli_query($conn,"

SELECT

u.*,
a.full_name,
a.phone_number

FROM users u

LEFT JOIN admins a
ON a.user_id=u.id

WHERE u.role='admin'

ORDER BY u.id DESC

");

?>

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

<div class="content">


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

    <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>

    <!-- ================= GRID ================= -->

    <div class="adminGrid">

        <!-- ================= FORM CARD ================= -->

        <div class="whiteSection">

            <div class="sectionHeader">

                <div class="sectionTitle">
                    Create Admin Account
                </div>

                <div class="sectionSub">
                    Add new administrator access
                </div>

            </div>

            <?php if($msg!=""){ ?>

                <div class="alert <?= $type ?>">

                    <?= $msg ?>

                </div>

            <?php } ?>

            <form
            method="POST"
            class="adminForm"
            >

                <div class="formGroup">

                    <label>
                        Full Name
                    </label>

                    <input
                    type="text"
                    name="full_name"
                    placeholder="Enter full name"
                    required
                    >

                </div>

                <div class="formGroup">

                    <label>
                        Phone Number
                    </label>

                    <input
                    type="text"
                    name="phone_number"
                    placeholder="Enter phone number"
                    required
                    >

                </div>

                <div class="formGroup">

                    <label>
                        Email Address
                    </label>

                    <input
                    type="email"
                    name="email"
                    placeholder="example@usm.my"
                    required
                    >

                </div>

                <button
                type="submit"
                name="add_subadmin"
                class="btn btnBlue"
                >

                Create Admin

                </button>

            </form>

        </div>

        <!-- ================= LIST CARD ================= -->

        <div class="whiteSection">

            <div class="sectionHeader">

                <div class="sectionTitle">
                    Admin List
                </div>

                <div class="sectionSub">
                    Current registered admin accounts
                </div>

            </div>

            <div class="tableWrap">

            <table>

                <tr>

                    <th>Name</th>
                    <th>Phone</th>
                    <th>Email</th>

                </tr>

                <?php while($row=mysqli_fetch_assoc($admins)){ ?>

                <tr>

                    <td>

                    <?= htmlspecialchars($row['full_name']) ?>

                    </td>

                    <td>

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

                    </td>

                    <td>

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

                    </td>

                </tr>

                <?php } ?>

            </table>

            </div>

        </div>

    </div>

</div>

<script>

/* =========================
   LOADING BUTTON
========================= */

const form =
document.querySelector(".adminForm");

const submitBtn =
document.querySelector(
"button[type='submit']"
);

form.addEventListener(
"submit",
function(){

submitBtn.innerHTML =
"Processing...";

submitBtn.disabled = true;

}
);

</script>