<?php
//////////////// DEFAULT NULL VALUES ///////////////
$error = array();
$date = date('d/M/Y');
$select = "--select--";
$time = date('h:m:s');
?>
<?php
if (isset($_POST['staff_register_btn'])) {
    $username = inject_checker($connection, $_POST['username']);
    $password = inject_checker($connection, $_POST['password']);
    $name = inject_checker($connection, ucfirst($_POST['name']));
    $role = inject_checker($connection, ucwords($_POST['role']));
    $dob = inject_checker($connection, $_POST['dob']);
    $lga = inject_checker($connection, ucwords($_POST['lga']));
    $state = inject_checker($connection, ucwords($_POST['state']));
    $country = inject_checker($connection, ucwords($_POST['country']));
    $sex = inject_checker($connection, $_POST['sex']);
    $address = inject_checker($connection, ucwords($_POST['address']));
    $phone = inject_checker($connection, $_POST['phone']);
    $email = inject_checker($connection, strtolower($_POST['email']));
    $status = "Active";
    $date = date("Y-m-d H:i:s"); // Current timestamp
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Validation
    if (
        empty($username) || empty($password) || empty($name) || empty($role) || empty($dob) || empty($lga) ||
        empty($state) || empty($country) || empty($sex) || empty($address) || empty($phone) || empty($email)
    ) {
        $_SESSION['msg'] = "All fields required";
        $_SESSION['type'] = "error";
    } else {
        // Check if username exists
        $stmt = $connection->prepare("SELECT id FROM staff WHERE username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $_SESSION['msg'] = "Username already exists";
            $_SESSION['type'] = "error";
            $stmt->close();
        } else {
            $stmt->close();

            // Check if email exists
            $stmt = $connection->prepare("SELECT id FROM staff WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();

            if ($stmt->num_rows > 0) {
                $_SESSION['msg'] = "Email already exists";
                $_SESSION['type'] = "error";
                $stmt->close();
            } else {
                $stmt->close();

                // T06 FIX: Handle image upload with MIME validation
                $image_location = "uploads/staff/none.jpg"; // default
                if (!empty($_FILES['file']['name'])) {
                    $upload_error = validate_image_upload('file');
                    if ($upload_error !== null) {
                        $_SESSION['msg'] = $upload_error;
                        $_SESSION['type'] = "error";
                        header("Location: add_staff");
                        exit();
                    }
                    $saved_path = save_uploaded_image('file', 'uploads/staff/');
                    if ($saved_path !== false) {
                        $image_location = $saved_path;
                    }
                }

                // Insert staff with prepared statement
                $stmt = $connection->prepare("INSERT INTO staff (username, password, name, role, dob, lga, state, country, sex, address, phone, email, status, passport, date_registered) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->bind_param("sssssssssssssss", $username, $hashed_password, $name, $role, $dob, $lga, $state, $country, $sex, $address, $phone, $email, $status, $image_location, $date);

                if ($stmt->execute()) {
                    $_SESSION['msg'] = "Staff Registration Successful";
                    $_SESSION['type'] = "success";
                } else {
                    $_SESSION['msg'] = "Staff Registration Failed";
                    $_SESSION['type'] = "error";
                }

                $stmt->close();
            }
        }
    }

    // Redirect after action
    header("Location: add_staff");
    exit();
}
?>


<div class="page-title">
    <div>
        <h1><i class="fa fa-calendar"></i> Staff</h1>
        <p>Add Staff</p>
    </div>    
</div>
<div class="card">
    <form action='' method='POST' enctype="multipart/form-data">
        <div class='panel panel-primary ch'>
            <div class='panel-heading'>
                <h4 class='text-center'>Add New Staff</h4>
            </div>
            <div class='panel-body'>
                <div class='row'>
                    <div class='col-xs-12 col-sm-12 col-md-12'>
                        <table class='table table-striped'>
                            <!-- Profile Image Upload with Preview -->
                <div class='form-group text-center'>
                    <label for='uploadImage'><b>Upload Staff Image</b></label><br>
                    <img id='preview' src='../uploads/staff/none.jpg' class='img-thumbnail rounded-circle mb-2' width='150' height='150' alt='Profile Preview'>
                    <input type='file' name='file' id='uploadImage' class='form-control-file d-block mx-auto' onchange="previewImage(event)" required>
                </div>
                            <tr>
                                <td>Username</td>
                                <td>
                                    <input type='text' value='' name='username' class='form-control' required>
                                </td>
                            </tr>
                            <tr>
                                <td>Password</td>
                                <td>
                                    <input type='password' value='' name='password' class='form-control' required>
                                </td>
                            </tr>
                            <tr>
                                <td>Name</td>
                                <td>
                                    <input type='text' value='' name='name' placeholder=' Full Name' class='form-control' required>
                                </td>
                            </tr>
                           
                                <!-- Date of Birth -->                    
					<tr>
                        <td>Date of Birth</td>
                        <td><input type='text' name='dob' class='form-control datepicker' required></td>
                    </tr>
                            </tr>
                            <tr>
                                <td>Role</td>
                                <td>
                                    <select name='role' class='form-control' required>
                                <option>Select Role</option>
                                <?php
                                $query = "SELECT * FROM `role`";
                                $run_query = mysqli_query($connection, $query);
                                if (mysqli_num_rows($run_query) > 0) {
                                    while ($result = mysqli_fetch_assoc($run_query)) {
                                        $all_role = $result['role_name'];
                                        echo "<option>{$all_role}</option>";
                                    }
                                }
                                ?>
                            </select>
                                </td>
                            </tr>
                            <tr>
                                <td>Country</td>
                                <td>
                                    <input type='text' value='Nigeria' name='country' placeholder='Country' class='form-control' required>
                                </td>
                            </tr>
                            <tr>
                                <td>State</td>
                                <td>
                                    <select name="state" id="state" class="form-control" onchange="toggleLGA(this);">
                                <option value="">- Select -</option>
                                <?php
                                $states = ["Abia", "Adamawa", "AkwaIbom", "Anambra", "Bauchi", "Bayelsa", "Benue", "Borno",
                                    "Cross River", "Delta", "Ebonyi", "Edo", "Ekiti", "Enugu", "FCT", "Gombe", "Imo",
                                    "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi", "Kwara", "Lagos", "Nasarawa",
                                    "Niger", "Ogun", "Ondo", "Osun", "Oyo", "Plateau", "Rivers", "Sokoto", "Taraba",
                                    "Yobe", "Zamfara"];
                                foreach ($states as $state) echo "<option value='$state'>$state</option>";
                                ?>
                            </select>
                                </td>
                            </tr>

                            <tr>
                                <td>LGA</td>
                                <td>
                                    <select name="lga" id="lga" class="form-control select-lga" required>
                                    </select>
                                </td>
                            </tr>

                            <tr>
                                <td>Sex</td>
                                <td>
                                    <select name='sex' class='form-control' required>
                                        <option>Male</option>
                                        <option>Female</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td>Staff Address</td>
                                <td>
                                    <input type='text' name='address' placeholder='Staff Address' class='form-control'
                                        value=''
                                        required>
                                </td>
                            </tr>
                            <tr>
                                <td>Staff Phone Number</td>
                                <td>
                                    <div class="input-group">
                                        <input name="phone" pattern="[0-9]+" title="Input must be a valid phone number" value='' required="" class="form-control" placeholder="Phone Number" aria-describedby="basic-addon2" type="phone">
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>Staff Email</td>
                                <td>
                                    <input type='email' name='email' placeholder='Staff Email e.g me@gmail.com' class='form-control'>
                                </td>
                            </tr>
                        </table>
                        <div class='col-xs-12 col-sm-12 col-md-6'></div>
                        <div class='col-xs-12 col-sm-12 col-md-6'>
                            <button type='submit' name='staff_register_btn' class='btn btn-primary'>Register</button>
                        </div>
                        <br><br>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
