<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');

try {
    $role_id = intval($_POST['role_id'] ?? 0);
    $role_name = trim($_POST['role_name'] ?? '');
    $status = trim($_POST['status'] ?? 'Active');

    if ($role_id <= 0) { echo json_encode(["status"=>"error","message"=>'Invalid role id']); exit; }
    $errors = [];
    if ($role_name === '' || mb_strlen($role_name) < 2) { $errors[] = 'Role Name must be at least 2 characters.'; }
    if (!in_array($status, ['Active','Inactive'])) { $errors[] = 'Invalid status.'; }
    if ($errors) { echo json_encode(["status"=>"error","message"=>$errors]); exit; }

    // Ensure unique role name (exclude current id)
    $chk = $pdo->prepare("SELECT COUNT(*) FROM staff_role_types WHERE LOWER(role_name)=LOWER(?) AND role_id <> ?");
    $chk->execute([$role_name, $role_id]);
    if ($chk->fetchColumn() > 0) { echo json_encode(["status"=>"error","message"=>"Role name already exists."]); exit; }

    // Read before
    $before = $pdo->prepare("SELECT role_name, status FROM staff_role_types WHERE role_id = ?");
    $before->execute([$role_id]);
    $beforeRow = $before->fetch(PDO::FETCH_ASSOC) ?: [];

    $stmt = $pdo->prepare("UPDATE staff_role_types SET role_name = ?, status = ?, updated_at = NOW() WHERE role_id = ?");
    $stmt->execute([$role_name, $status, $role_id]);

    write_audit_log($pdo, [
        'module' => 'People',
        'action' => 'update',
        'entity_table' => 'staff_role_types',
        'entity_id' => $role_id,
        'before_data' => $beforeRow,
        'after_data' => ['role_name'=>$role_name,'status'=>$status],
        'message' => 'Staff role updated'
    ]);

    echo json_encode(["status"=>"success","message"=>"Role updated successfully."]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(["status"=>"error","message"=> $e->getMessage()]);
}
?>


