<?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 = (int) $_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();

                // Handle image upload
                $image_location = "uploads/staff/none.jpg"; // default
                if (!empty($_FILES['file']['name'])) {
                    $uploadDir = 'uploads/staff/';
                    $filename = basename($_FILES['file']['name']);
                    $targetFile = $uploadDir . $filename;
                    if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
                        $image_location = $targetFile;
                    }
                }

                // 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("sssisssssssssss", $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: staff");
    exit();
}
?>

<?php
if (isset($_POST['update_staff_btn'])) {
    $id = (int) $_POST['edit_staff_id'];
    $username = inject_checker($connection, $_POST['username']);
    $name = inject_checker($connection, ucfirst($_POST['name']));
    $role = (int) $_POST['role'];
    $dob = inject_checker($connection, $_POST['dob']);
    $lga = inject_checker($connection, $_POST['lga']);
    $state = inject_checker($connection, $_POST['state']);
    $country = inject_checker($connection, $_POST['country']);
    $sex = inject_checker($connection, $_POST['sex']);
    $address = inject_checker($connection, $_POST['address']);
    $phone = inject_checker($connection, $_POST['phone']);
    $email = inject_checker($connection, strtolower($_POST['email']));

    // 1. Validate unique username (excluding current staff)
    $stmt = $connection->prepare("SELECT id FROM staff WHERE username = ? AND id != ?");
    $stmt->bind_param("si", $username, $id);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows > 0) {
        $_SESSION['msg'] = "Username already exists.";
        $_SESSION['type'] = "error";
        $stmt->close();
        header("Location: staff");
        exit();
    }
    $stmt->close();

    // 2. Validate unique email (excluding current staff)
    $stmt = $connection->prepare("SELECT id FROM staff WHERE email = ? AND id != ?");
    $stmt->bind_param("si", $email, $id);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows > 0) {
        $_SESSION['msg'] = "Email already exists.";
        $_SESSION['type'] = "error";
        $stmt->close();
        header("Location: staff");
        exit();
    }
    $stmt->close();

    // 3. Image upload logic
    $passport = ""; // Default empty unless new image uploaded
    if (!empty($_FILES['file']['name'])) {
        $fileName = basename($_FILES['file']['name']);
        $tmp_name = $_FILES['file']['tmp_name'];
        $uploadDir = "uploads/staff/";
        $targetPath = $uploadDir . $fileName;

        if (move_uploaded_file($tmp_name, $targetPath)) {
            $passport = $targetPath;
        }
    }

    // 4. Perform the update using prepared statement
    if ($passport !== "") {
        $query = "UPDATE staff SET username=?, name=?, role=?, dob=?, lga=?, state=?, country=?, sex=?, address=?, phone=?, email=?, passport=? WHERE id=?";
        $stmt = $connection->prepare($query);
        $stmt->bind_param("ssisssssssssi", $username, $name, $role, $dob, $lga, $state, $country, $sex, $address, $phone, $email, $passport, $id);
    } else {
        $query = "UPDATE staff SET username=?, name=?, role=?, dob=?, lga=?, state=?, country=?, sex=?, address=?, phone=?, email=? WHERE id=?";
        $stmt = $connection->prepare($query);
        $stmt->bind_param("ssissssssssi", $username, $name, $role, $dob, $lga, $state, $country, $sex, $address, $phone, $email, $id);
    }

    // 5. Execute and give feedback
    if ($stmt->execute() && $stmt->affected_rows > 0) {
        $_SESSION['msg'] = "Staff updated successfully.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "No changes made or update failed.";
        $_SESSION['type'] = "error";
    }

    $stmt->close();
    header("Location: staff");
    exit();
}
?>


<?php
    //////////////// POST ACTION TO CHANGE staff STATUS ///
    if(isset($_POST['change_status_btn'])){
        $status_id = $_POST['staff_hidden_id'];
        $staff_status = $_POST['new_status'];

        $query = " UPDATE `staff` SET 
                                    `status` = '{$staff_status}' WHERE `id` = '{$status_id}' ";
        $run_query = mysqli_query($connection, $query);

        if($run_query == true){
            $_SESSION['msg'] = "Staff Status Changed";
        		$_SESSION['type'] = "success";  
        }else{
            $_SESSION['msg'] = "Staff Status Changed Failed.";
        		$_SESSION['type'] = "error";  
        }
        // Redirect once after logic
    header("Location: staff");
    exit();
    }
?>

<?php
if (isset($_POST['staff_delete_btn'])) {
    $delete_id = $_POST['staff_hidden_id']; // Staff ID to delete

    if (!empty($delete_id)) {
            // Delete the Staff
            $query2 = "DELETE FROM `staff` WHERE `id` = ?";
            $stmt2 = $connection->prepare($query2);
            $stmt2->bind_param("i", $delete_id);
            $result2 = $stmt2->execute();
            $stmt2->close();

            if($run_query == true){
            	$_SESSION['msg'] = "Staff and Related Records Deleted Successfully";
        		$_SESSION['type'] = "success";
                
            } else {
            $_SESSION['msg'] = "Staff Record not Deleted.";
        	$_SESSION['type'] = "error";                
            }        
   }
   // Redirect once after logic
    header("Location: staff");
    exit();
    
}
?>


