<?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";
    }

    /* FULL NAME */

    if(strlen($full_name) < 6){

        $errors[] =
        "Full name must be at least 6 characters";
    }

    if(preg_match('/[0-9]/',$full_name)){

        $errors[] =
        "Full name cannot contain numbers";
    }

    /* 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[] =
        "Phone number must start with 01 and contain 10-11 digits";
    }

    /* 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">

<style>

.liveError{

    color:#e53935;
    font-size:13px;
    margin-top:5px;
    display:block;
}

</style>

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

                <!-- FULL NAME -->

                <div class="formGroup">

                    <label>
                        Full Name
                    </label>

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

                    <small
                    id="nameError"
                    class="liveError"
                    ></small>

                </div>

                <!-- PHONE -->

                <div class="formGroup">

                    <label>
                        Phone Number
                    </label>

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

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

                </div>

                <!-- EMAIL -->

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

/* =========================
   ELEMENTS
========================= */

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

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

const fullName =
document.getElementById("full_name");

const phone =
document.getElementById("phone_number");

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

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

/* =========================
   FULL NAME VALIDATION
========================= */

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

    let value =
    fullName.value;

    /* REMOVE NUMBERS */

    value =
    value.replace(/[0-9]/g,'');

    fullName.value =
    value;

    if(value.length < 6){

        nameError.innerHTML =
        "Full name must be at least 6 characters";

    }else{

        nameError.innerHTML = "";
    }

}
);

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

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

    let value =
    phone.value.replace(/[^0-9]/g,'');

    /* LIMIT 11 DIGITS */

    value =
    value.substring(0,11);

    phone.value =
    value;

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

        phoneError.innerHTML =
        "Phone number must start with 01";

    }
    else if(value.length < 10){

        phoneError.innerHTML =
        "Phone number must be at least 10 digits";

    }
    else{

        phoneError.innerHTML = "";
    }

}
);

/* =========================
   FORM SUBMIT
========================= */

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

    let hasError = false;

    /* FULL NAME CHECK */

    if(
        fullName.value.length < 6
    ){

        nameError.innerHTML =
        "Full name must be at least 6 characters";

        hasError = true;
    }

    /* PHONE CHECK */

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

        phoneError.innerHTML =
        "Phone number must start with 01";

        hasError = true;
    }

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

        phoneError.innerHTML =
        "Phone number must contain 10-11 digits";

        hasError = true;
    }

    if(hasError){

        e.preventDefault();
        return;
    }

    submitBtn.innerHTML =
    "Processing...";

    submitBtn.disabled = true;

}
);

</script>