<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
session_write_close();
date_default_timezone_set('Africa/Lagos');
require 'config.php';

// Authorization protection step
if (!isset($_SESSION['user_id']) || !in_array(strtolower(trim($_SESSION['role'])), ['hr', 'admin', 'superadmin'])) {
    die("Access Denied: Administrative Clearance Required.");
}

/*
|--------------------------------------------------------------------------
| ROUTER ACTION: CREATE USER DIRECTORY PROFILE
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create') {
    $newUsername = trim($_POST['username']);
    $plainPassword = $_POST['password'];
    $newRole = $_POST['role'];
    $deptId = !empty($_POST['department_id']) ? intval($_POST['department_id']) : null;
    $mustChangePass = isset($_POST['must_change_password']) ? 1 : 0;
    $canAddStaff = isset($_POST['can_add_staff']) ? 1 : 0;

    $hashedPassword = password_hash($plainPassword, PASSWORD_DEFAULT);

    $stmt = $conn->prepare("
        INSERT INTO users (username, password, role, department_id, must_change_password, can_add_staff)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("sssiii", $newUsername, $hashedPassword, $newRole, $deptId, $mustChangePass, $canAddStaff);
    
    if ($stmt->execute()) {
        header("Location: manage_users.php?msg=created");
    } else {
        header("Location: manage_users.php?err=" . urlencode($stmt->error));
    }
    exit;
}

/*
|--------------------------------------------------------------------------
| ROUTER ACTION: UPDATE EXISTING USER DETAILS
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
    $userId = intval($_POST['user_id']);
    $newUsername = trim($_POST['username']);
    $newRole = $_POST['role'];
    $deptId = !empty($_POST['department_id']) ? intval($_POST['department_id']) : null;
    $mustChangePass = isset($_POST['must_change_password']) ? 1 : 0;
    $canAddStaff = isset($_POST['can_add_staff']) ? 1 : 0;

    // Check if an administrative password override was provided
    if (!empty($_POST['password'])) {
        $hashedPassword = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $stmt = $conn->prepare("
            UPDATE users 
            SET username = ?, password = ?, role = ?, department_id = ?, must_change_password = ?, can_add_staff = ? 
            WHERE id = ?
        ");
        $stmt->bind_param("sssiiii", $newUsername, $hashedPassword, $newRole, $deptId, $mustChangePass, $canAddStaff, $userId);
    } else {
        // Keep existing password
        $stmt = $conn->prepare("
            UPDATE users 
            SET username = ?, role = ?, department_id = ?, must_change_password = ?, can_add_staff = ? 
            WHERE id = ?
        ");
        $stmt->bind_param("ssiiii", $newUsername, $newRole, $deptId, $mustChangePass, $canAddStaff, $userId);
    }

    if ($stmt->execute()) {
        header("Location: manage_users.php?msg=updated");
    } else {
        header("Location: manage_users.php?err=" . urlencode($stmt->error));
    }
    exit;
}

/*
|--------------------------------------------------------------------------
| ROUTER ACTION: DELETE ACCOUNT PROFILE
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $userId = intval($_POST['user_id']);

    // Prevent self-deletion safety protocol
    if ($userId === intval($_SESSION['user_id'])) {
        header("Location: manage_users.php?err=" . urlencode("Security Conflict: Deleting your current session instance is prohibited."));
        exit;
    }

    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param("i", $userId);

    if ($stmt->execute()) {
        header("Location: manage_users.php?msg=deleted");
    } else {
        header("Location: manage_users.php?err=" . urlencode($stmt->error));
    }
    exit;
}