<?php
require_once 'init.php';

if (!userHasRole(['Admin', 'Manager'])) {
    http_response_code(403);
    echo json_encode(['status' => 'error', 'message' => 'Permission denied.']);
    exit();
}

$data = json_decode(file_get_contents('php://input'), true);
$client_id = $data['client_id'] ?? null;
$item_key = $data['item_key'] ?? null;
$status = $data['status'] ?? false;

header('Content-Type: application/json');

if (!$client_id || !$item_key) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid data provided.']);
    exit();
}

// Sanitize the item_key to prevent SQL injection
$allowed_columns = ['seo_keywords', 'seo_link', 'google_photos', 'google_no', 'insta_highlights', 'insta_bio', 'insta_grid', 'whatsapp_logo', 'qr_code'];
if (!in_array($item_key, $allowed_columns)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid checklist item.']);
    exit();
}

$status_int = $status ? 1 : 0;

// Use a prepared statement to update the checklist item
// The column name cannot be parameterized directly, so we validate it from the allow-list
$stmt = $conn->prepare("UPDATE client_onboarding_checklist SET `$item_key` = ? WHERE client_id = ?");
$stmt->bind_param("ii", $status_int, $client_id);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success']);
} else {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Database update failed.']);
}
$stmt->close();
$conn->close();
?>