<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle CORS preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Debug-safe error logging
ini_set('display_errors', '0');
ini_set('log_errors', '1');
if (!ini_get('error_log')) {
    ini_set('error_log', __DIR__ . '/php-error.log');
}

// Include DB config
require_once __DIR__ . '/../unified_config.php';
if (function_exists('db')) {
    $conn = db();
} elseif (isset($conn) && $conn instanceof mysqli) {
    // ok
} else {
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "Database connection not configured"]);
    exit;
}

// Read POST data
$data = json_decode(file_get_contents("php://input"), true);
$admin_email = trim($data['admin_email'] ?? '');
$client_email = trim($data['client_email'] ?? '');
$action = trim($data['action'] ?? ''); // "suspend" or "unsuspend"

// Validate required inputs
if (!$admin_email || !$client_email || !in_array($action, ['suspend', 'unsuspend'])) {
    http_response_code(400);
    echo json_encode(["success" => false, "message" => "Required fields missing or invalid action"]);
    exit;
}

// Verify admin email exists
$stmt = $conn->prepare("SELECT * FROM adminlogins WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $admin_email);
$stmt->execute();
$admin = $stmt->get_result()->fetch_assoc();

if (!$admin) {
    http_response_code(401);
    echo json_encode(["success" => false, "message" => "Invalid admin email"]);
    exit;
}

// Fetch client
$stmt2 = $conn->prepare("SELECT * FROM loginusers WHERE email = ? LIMIT 1");
$stmt2->bind_param("s", $client_email);
$stmt2->execute();
$client = $stmt2->get_result()->fetch_assoc();

if (!$client) {
    http_response_code(404);
    echo json_encode(["success" => false, "message" => "Client not found"]);
    exit;
}

// Update suspend status
$new_status = ($action === 'suspend') ? 1 : 0;
$upd = $conn->prepare("UPDATE loginusers SET suspend = ? WHERE email = ? LIMIT 1");
$upd->bind_param("is", $new_status, $client_email);
$upd->execute();

// Response
echo json_encode([
    "success" => true,
    "message" => "Client account has been " . ($action === 'suspend' ? 'suspended' : 'unsuspended'),
    "user" => [
        "email" => $client['email'],
        "suspend" => $new_status
    ]
]);
exit;
?>
