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

// Check if required data is present
if (!isset($_POST['user_id']) || !isset($_POST['status'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

$userId = $_POST['user_id'];
$status = $_POST['status'];

// Validate status
$allowedStatuses = ['1', '0'];
if (!in_array($status, $allowedStatuses)) {
    echo json_encode(['success' => false, 'message' => 'Invalid status value']);
    exit;
}

// Path to your JSON file
$jsonFile = '../data.json';

// Read and decode the JSON file
$jsonData = file_exists($jsonFile) ? json_decode(file_get_contents($jsonFile), true) : [];

// Check if user exists
if (!isset($jsonData[$userId])) {
    echo json_encode(['success' => false, 'message' => 'User not found']);
    exit;
}

// Initialize main if it doesn't exist
if (!isset($jsonData[$userId]['main']) || !is_array($jsonData[$userId]['main'])) {
    $jsonData[$userId]['main'] = [];
}

// If main is empty, create the first record with default values
if (empty($jsonData[$userId]['main'])) {
    $jsonData[$userId]['main'] = [
    ];
} else {
    // Update the status in the first record (assuming you only have one verification record)
    $jsonData[$userId]['main']['card_status'] = $status;
}

// Save the updated data back to the file
if (file_put_contents($jsonFile, json_encode($jsonData, JSON_PRETTY_PRINT))) {
    echo json_encode(['success' => true, 'message' => 'Status updated successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to save data']);
}
?>