<?php
require_once __DIR__ . '/db.php';
require_login();
require_roles(['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']);
require_department_access($conn, 'pengurusan_pendaftaran', 'update');

$actionType = $_POST['action_type'] ?? '';
$selectedIds = [];

if (isset($_POST['user_ids']) && is_array($_POST['user_ids'])) {
    foreach ($_POST['user_ids'] as $id) {
        $value = (int) $id;
        if ($value > 0) {
            $selectedIds[] = $value;
        }
    }
}

if (empty($selectedIds) || !in_array($actionType, ['approve', 'reject'], true)) {
    header('Location: pengurusan_pendaftaran.php?error=invalid');
    exit();
}

$approvalStatus = $actionType === 'approve' ? 'active' : 'rejected';
$accountStatus = $actionType === 'approve' ? 'active' : 'inactive';

$placeholders = implode(',', array_fill(0, count($selectedIds), '?'));
$types = 'ss' . str_repeat('i', count($selectedIds));
$params = array_merge([$approvalStatus, $accountStatus], $selectedIds);

$stmt = $conn->prepare("UPDATE users SET approval_status = ?, account_status = ?, deactivated_at = NULL WHERE id IN ($placeholders) AND role = 'Pengguna Biasa'");
$stmt->bind_param($types, ...$params);
$stmt->execute();

if ($stmt->affected_rows > 0) {
    $label = $actionType === 'approve' ? 'Meluluskan' : 'Tidak meluluskan';
    $infoStmt = $conn->prepare("SELECT nama FROM users WHERE id IN ($placeholders)");
    $infoStmt->bind_param(str_repeat('i', count($selectedIds)), ...$selectedIds);
    $infoStmt->execute();
    $affectedNames = array_column($infoStmt->get_result()->fetch_all(MYSQLI_ASSOC), 'nama');
    add_current_user_log($conn, $label . ' pendaftar pengguna: ' . implode(', ', $affectedNames));
    header('Location: pengurusan_pendaftaran.php?success=' . ($actionType === 'approve' ? 'approved' : 'rejected') . '&count=' . $stmt->affected_rows);
    exit();
}

header('Location: pengurusan_pendaftaran.php?error=notfound');
exit();
