<?php
/**
 * Admin/auth/approve_admin.php
 * الموافقة على أو رفض طلبات انضمام المشرفين
 * مسموح فقط للسوبر أدمن
 */
require_once __DIR__ . '/../../connect.php';

if ($role !== 'super_admin') {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden. Super Admin access required.']);
    exit;
}

$targetId = filterRequest('admin_id');
$action   = filterRequest('action'); // approved, rejected, suspended

if (empty($targetId) || empty($action)) {
    jsonError("Admin ID and action are required.");
    exit;
}

if (!in_array($action, ['approved', 'rejected', 'suspended'])) {
    jsonError("Invalid action.");
    exit;
}

try {
    $con = Database::get('main');

    $sql = "UPDATE adminUser SET status = :status, approved_by = :by, approved_at = NOW() WHERE id = :id";
    $stmt = $con->prepare($sql);
    $stmt->execute([
        ':status' => $action,
        ':by'     => $user_id, // السوبر أدمن الحالي
        ':id'     => $targetId
    ]);

    if ($stmt->rowCount() > 0) {
        printSuccess(null, "Admin status updated to $action.");
    } else {
        jsonError("Admin not found or status already updated.");
    }

} catch (Exception $e) {
    error_log("[Approve Admin Error] " . $e->getMessage());
    jsonError("Server Error: " . $e->getMessage());
}
