<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn, ['admin', 'superadmin']);

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$user_id = intval($_GET['user_id'] ?? $_POST['user_id'] ?? 0);

if ($user_id <= 0) {
    header("Location: dashboard.php?error=invalid_id");
    exit();
}

// Dapatkan maklumat user sasaran
$stmt = $conn->prepare("SELECT email, role FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$target = $stmt->get_result()->fetch_assoc();

if (!$target) {
    header("Location: dashboard.php?error=user_not_found");
    exit();
}

// Elak edit superadmin lain (kecuali diri sendiri)
if ($target['role'] === 'superadmin' && $target['email'] !== $_SESSION['email']) {
    header("Location: dashboard.php?error=cannot_edit_superadmin");
    exit();
}

// PROSES: Tukar Role (Superadmin sahaja)
if ($action === 'change_role' && $_SERVER['REQUEST_METHOD'] === 'POST' && $_SESSION['role'] === 'superadmin') {
    $new_role = $_POST['new_role'] ?? '';
    if (!in_array($new_role, ['user', 'admin', 'superadmin'])) {
        header("Location: dashboard.php?error=invalid_role");
        exit();
    }
    // Hanya superadmin utama boleh set superadmin
    if ($new_role === 'superadmin' && $_SESSION['email'] !== 'syarafana@mainpp.gov.my') {
        header("Location: dashboard.php?error=permission_denied");
        exit();
    }
    $update = $conn->prepare("UPDATE users SET role = ? WHERE id = ?");
    $update->bind_param("si", $new_role, $user_id);
    if ($update->execute()) {
        logActivity(
            $conn,
            (int) ($_SESSION['user_id'] ?? 0),
            'update_user_role',
            'Kemaskini role user: ' . ($target['email'] ?? '') . ' kepada ' . $new_role . ' (User ID: ' . $user_id . ')'
        );
    }
    header("Location: dashboard.php?success=role_updated#user-roles");
    exit();
}

// PROSES: Approve User (Admin & Superadmin)
elseif ($action === 'approve' && in_array($_SESSION['role'], ['admin', 'superadmin'])) {
    $update = $conn->prepare("UPDATE users SET status = 'approved' WHERE id = ?");
    $update->bind_param("i", $user_id);
    if ($update->execute()) {
        logActivity($conn, (int) ($_SESSION['user_id'] ?? 0), 'update_user_status', 'Approve user: ' . ($target['email'] ?? '') . ' (User ID: ' . $user_id . ')');
    }
    header("Location: dashboard.php?success=user_approved#pending-users");
    exit();
}

// PROSES: Reject User (Admin & Superadmin)
elseif ($action === 'reject' && in_array($_SESSION['role'], ['admin', 'superadmin'])) {
    $update = $conn->prepare("UPDATE users SET status = 'rejected' WHERE id = ?");
    $update->bind_param("i", $user_id);
    if ($update->execute()) {
        logActivity($conn, (int) ($_SESSION['user_id'] ?? 0), 'update_user_status', 'Reject user: ' . ($target['email'] ?? '') . ' (User ID: ' . $user_id . ')');
    }
    header("Location: dashboard.php?success=user_rejected#pending-users");
    exit();
}

// Default redirect
header("Location: dashboard.php");
exit();
?>
