<?php
require_once __DIR__ . '/../config.php';
header('Content-Type: application/json');

$session_role = $_SESSION['user_role'] ?? ($_SESSION['role'] ?? '');
if (!isset($_SESSION['user_id']) || $session_role !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$customer_id = intval($data['customer_id'] ?? 0);

if ($customer_id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid customer ID']);
    exit;
}

try {
    $has_status_col = false;
    $col_check = $mysqli->query("SHOW COLUMNS FROM customers LIKE 'status'");
    if ($col_check && $col_check->num_rows > 0) {
        $has_status_col = true;
    }
    if (!$has_status_col) {
        $mysqli->query("ALTER TABLE customers ADD COLUMN status ENUM('active','inactive') DEFAULT 'active'");
        $mysqli->query("UPDATE customers SET status = 'active' WHERE status IS NULL OR status = ''");
    }

    $stmt = $mysqli->prepare("SELECT id, firstname, lastname, email, status FROM customers WHERE id = ? LIMIT 1");
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }
    $stmt->bind_param('i', $customer_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $customer = $result->fetch_assoc();
    $stmt->close();

    if (!$customer) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Customer not found']);
        exit;
    }

    $current_status = strtolower(trim((string)($customer['status'] ?? 'active')));
    $new_status = $current_status === 'active' ? 'inactive' : 'active';

    $update = $mysqli->prepare("UPDATE customers SET status = ? WHERE id = ?");
    if (!$update) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }
    $update->bind_param('si', $new_status, $customer_id);
    if (!$update->execute()) {
        throw new Exception('Execute failed: ' . $update->error);
    }
    $update->close();

    echo json_encode([
        'success' => true,
        'message' => $new_status === 'active' ? 'Customer activated successfully' : 'Customer suspended successfully',
        'customer' => [
            'id' => $customer_id,
            'status' => $new_status
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error changing customer status: ' . $e->getMessage()]);
}

$mysqli->close();
?>
