<?php
// hr_api/manage_users.php



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

// Include the reusable CORS handler
require_once __DIR__ . '/cors.php';

session_start();
require_once __DIR__ . '/db.php';

if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentication required.']);
    exit();
}

$current_user_role = $_SESSION['user_role'];

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        if ($current_user_role === 'admin' || $current_user_role === 'senior_hr' || $current_user_role === 'regional_hr') {
            try {
                $sql = "SELECT id, name, username, email, role, region, department, status FROM users";
                $params = [];

                if ($current_user_role === 'regional_hr') {
                    $sql .= " WHERE region = :region";
                    $params['region'] = $_SESSION['user_region'];
                }

                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
                echo json_encode(['success' => true, 'users' => $users]);
            } catch (PDOException $e) {
                http_response_code(500);
                echo json_encode(['success' => false, 'message' => 'Database error fetching users: ' . $e->getMessage()]);
            }
        } else {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Access Denied: Insufficient privileges.']);
        }
        break;

    case 'POST':
        // --- MODIFICATION 1: Allow regional_hr to use POST ---
        if (!in_array($current_user_role, ['admin', 'senior_hr', 'regional_hr'])) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Access Denied: Only HR staff can create users.']);
            exit();
        }
        
        $input = json_decode(file_get_contents('php://input'), true);

        $username = $input['username'] ?? '';
        $email = $input['email'] ?? '';
        $password = $input['password'] ?? '';
        $role = $input['role'] ?? 'staff';
        $name = $input['name'] ?? null;
        $region = $input['region'] ?? null;
        $department = $input['department'] ?? null;
        $status = $input['status'] ?? 'active';

        // --- MODIFICATION 2: NEW LOGIC FOR REGIONAL HR ---
        if ($current_user_role === 'regional_hr') {
            // Regional HR can only create HOD users.
            if ($role !== 'hod') {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Regional HR can only create HOD users.']);
                exit();
            }
            // Automatically assign the HOD to the Regional HR's own region.
            $region = $_SESSION['user_region'];
        }

        if (empty($username) || empty($email) || empty($password) || empty($role) || empty($status)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Username, email, password, role, and status are required.']);
            exit();
        }

        if ($role === 'regional_hr' && empty($region)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Region is required for a Regional HR.']);
            exit();
        }

        if ($role === 'hod' && empty($department)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Department is required for a HOD.']);
            exit();
        }
        
        if ($current_user_role !== 'admin' && $role === 'admin') {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Only an admin can create another admin.']);
            exit();
        }

        try {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE username = :username OR email = :email");
            $stmt->execute(['username' => $username, 'email' => $email]);
            if ($stmt->rowCount() > 0) {
                http_response_code(409);
                echo json_encode(['success' => false, 'message' => 'Username or email already exists.']);
                exit();
            }

            $hashed_password = password_hash($password, PASSWORD_DEFAULT);

            $stmt = $pdo->prepare("INSERT INTO users (name, username, email, password, role, region, department, status) VALUES (:name, :username, :email, :password, :role, :region, :department, :status)");
            if ($stmt->execute([
                'name' => $name,
                'username' => $username,
                'email' => $email,
                'password' => $hashed_password,
                'role' => $role,
                'region' => $region,
                'department' => $department,
                'status' => $status
            ])) {
                echo json_encode(['success' => true, 'message' => 'User added successfully.']);
            } else {
                http_response_code(500);
                echo json_encode(['success' => false, 'message' => 'Failed to add user: ' . $stmt->errorInfo()[2]]);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Database error adding user: ' . $e->getMessage()]);
        }
        break;

    case 'PUT':
        if ($current_user_role !== 'admin' && $current_user_role !== 'senior_hr' && $current_user_role !== 'regional_hr') {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Access Denied: You do not have permission to update users.']);
            exit();
        }

        $input = json_decode(file_get_contents('php://input'), true);

        $user_id = $input['id'] ?? null;
        $username = $input['username'] ?? null;
        $email = $input['email'] ?? null;
        $role = $input['role'] ?? null;
        $password = $input['password'] ?? null;
        $name = $input['name'] ?? null;
        $region = $input['region'] ?? null;
        $department = $input['department'] ?? null;
        $status = $input['status'] ?? null;

        if (empty($user_id) || empty($username) || empty($email) || empty($role) || empty($status)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Missing ID, username, email, role or status for update.']);
            exit();
        }

        try {
            $stmt_check_target_user = $pdo->prepare("SELECT role, region FROM users WHERE id = :user_id LIMIT 1");
            $stmt_check_target_user->execute(['user_id' => $user_id]);
            $target_user_data = $stmt_check_target_user->fetch(PDO::FETCH_ASSOC);

            if (!$target_user_data) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'User not found.']);
                exit();
            }

            $target_user_current_role = $target_user_data['role'];

            // --- NEW LOGIC: Prevent changing the role of an Admin user ---
            if ($target_user_current_role === 'admin' && $role !== $target_user_current_role) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'You cannot change the role of an administrator.']);
                exit();
            }

            if ($current_user_role === 'senior_hr' && ($target_user_current_role === 'admin' || $role === 'admin')) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Senior HR cannot modify an administrator account.']);
                exit();
            }

            if ($current_user_role === 'regional_hr') {
                if ($target_user_data['region'] !== $_SESSION['user_region']) {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Regional HR can only modify users in their own region.']);
                    exit();
                }
                
                if ($role !== $target_user_current_role) {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Regional HR cannot change a user\'s role.']);
                    exit();
                }
                
                if ($region !== $target_user_data['region']) {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Regional HR cannot change a user\'s region.']);
                    exit();
                }

                if ($target_user_current_role === 'admin' || $target_user_current_role === 'senior_hr' || $role === 'admin' || $role === 'senior_hr') {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Regional HR cannot modify admin or senior HR accounts.']);
                    exit();
                }
            }
            
            if ($role === 'regional_hr' && empty($region)) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Region is required for a Regional HR.']);
                exit();
            }

            if ($role === 'hod' && empty($department)) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Department is required for a HOD.']);
                exit();
            }
            
            if ($password && strlen($password) < 6) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'New password must be at least 6 characters.']);
                exit();
            }

            $stmt_check_dupes = $pdo->prepare("SELECT id FROM users WHERE (username = :username OR email = :email) AND id != :id");
            $stmt_check_dupes->execute(['username' => $username, 'email' => $email, 'id' => $user_id]);
            if ($stmt_check_dupes->rowCount() > 0) {
                http_response_code(409);
                echo json_encode(['success' => false, 'message' => 'Username or email already exists for another user.']);
                exit();
            }

            $sql = "UPDATE users SET username = :username, email = :email, role = :role, region = :region, department = :department, status = :status";
            $params = [
                'username' => $username,
                'email' => $email,
                'role' => $role,
                'region' => $region,
                'department' => $department,
                'status' => $status,
                'id' => $user_id
            ];

            if ($password) {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $sql .= ", password = :password";
                $params['password'] = $hashed_password;
            }

            $sql .= " WHERE id = :id";

            $stmt = $pdo->prepare($sql);
            if ($stmt->execute($params)) {
                echo json_encode(['success' => true, 'message' => 'User updated successfully.']);
            } else {
                http_response_code(500);
                echo json_encode(['success' => false, 'message' => 'Failed to update user: ' . $stmt->errorInfo()[2]]);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Database error updating user: ' . $e->getMessage()]);
        }
        break;

    case 'PATCH':
        if ($current_user_role !== 'admin' && $current_user_role !== 'senior_hr' && $current_user_role !== 'regional_hr') {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Access Denied: You do not have permission to change user status.']);
            exit();
        }

        $input = json_decode(file_get_contents('php://input'), true);

        $user_id = $input['id'] ?? null;
        $new_status = $input['status'] ?? null;

        if (empty($user_id) || empty($new_status)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Missing user ID or new status.']);
            exit();
        }

        if (!in_array($new_status, ['active', 'inactive'])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid status value. Must be "active" or "inactive".']);
            exit();
        }

        try {
            $current_user_id = $_SESSION['user_id'];
            $target_user_data = null;

            $stmt_check_role = $pdo->prepare("SELECT role, region FROM users WHERE id = :user_id LIMIT 1");
            $stmt_check_role->execute(['user_id' => $user_id]);
            $target_user_data = $stmt_check_role->fetch(PDO::FETCH_ASSOC);

            if (!$target_user_data) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'User not found.']);
                exit();
            }
            $target_user_role = $target_user_data['role'];

            if ($user_id == $current_user_id) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'You cannot change your own account status.']);
                exit();
            }

            if ($current_user_role === 'senior_hr' && ($target_user_role === 'admin' || $target_user_role === 'senior_hr')) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Senior HR cannot change the status of an administrator or another Senior HR.']);
                exit();
            }
            
            if ($current_user_role === 'regional_hr') {
                if ($target_user_data['region'] !== $_SESSION['user_region']) {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Regional HR can only change status for users in their own region.']);
                    exit();
                }
                if ($target_user_role === 'admin' || $target_user_role === 'senior_hr' || $target_user_role === 'regional_hr') {
                    http_response_code(403);
                    echo json_encode(['success' => false, 'message' => 'Regional HR cannot change the status of another HR or admin account.']);
                    exit();
                }
            }

            $stmt = $pdo->prepare("UPDATE users SET status = :status WHERE id = :id");
            if ($stmt->execute(['status' => $new_status, 'id' => $user_id])) {
                echo json_encode(['success' => true, 'message' => 'User status updated successfully.']);
            } else {
                http_response_code(500);
                echo json_encode(['success' => false, 'message' => 'Failed to update user status: ' . $stmt->errorInfo()[2]]);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Database error updating user status: ' . $e->getMessage()]);
        }
        break;

    case 'DELETE':
        if ($current_user_role !== 'admin' && $current_user_role !== 'senior_hr') {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Access Denied: Only admins and senior HR can delete users.']);
            exit();
        }

        $input = json_decode(file_get_contents('php://input'), true);
        $user_id = $input['id'] ?? null;

        if (empty($user_id)) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'User ID is required for deletion.']);
            exit();
        }

        try {
            if ($user_id == $_SESSION['user_id']) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'You cannot delete your own account.']);
                exit();
            }

            $stmt_check_role = $pdo->prepare("SELECT role FROM users WHERE id = :user_id LIMIT 1");
            $stmt_check_role->execute(['user_id' => $user_id]);
            $target_user_data = $stmt_check_role->fetch(PDO::FETCH_ASSOC);

            if (!$target_user_data) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'User not found for deletion.']);
                exit();
            }

            $target_user_role = $target_user_data['role'];

            if (($current_user_role === 'admin' && $target_user_role === 'admin') || ($current_user_role === 'senior_hr' && ($target_user_role === 'admin' || $target_user_role === 'senior_hr'))) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'You cannot delete this type of account.']);
                exit();
            }

            $stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
            if ($stmt->execute(['id' => $user_id])) {
                if ($stmt->rowCount() > 0) {
                    echo json_encode(['success' => true, 'message' => 'User deleted successfully.']);
                } else {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'User not found or already deleted.']);
                }
            } else {
                http_response_code(500);
                echo json_encode(['success' => false, 'message' => 'Failed to delete user: ' . $stmt->errorInfo()[2]]);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Database error deleting user: ' . $e->getMessage()]);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed.']);
        break;
}
?>