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

$filePath = __DIR__ . '/../database/whatsapp_settings.json';

try {
    $input = json_decode(file_get_contents('php://input'), true);

    if (!is_array($input)) {
        throw new Exception("Invalid input data.");
    }

    // Read existing data
    $existingData = [];
    if (file_exists($filePath)) {
        $data = file_get_contents($filePath);
        $existingData = json_decode($data, true);
        if (!is_array($existingData)) $existingData = [];
    }

    // Merge input into existing data
    foreach ($input as $event => $info) {
        if (!isset($existingData[$event])) {
            $existingData[$event] = ["enabled" => false, "message" => ""];
        }
        if (isset($info['enabled'])) {
            $existingData[$event]['enabled'] = (bool)$info['enabled'];
        }
        if (isset($info['message'])) {
            $existingData[$event]['message'] = $info['message'];
        }
    }

    // Save to file
    file_put_contents($filePath, json_encode($existingData, JSON_PRETTY_PRINT));

    echo json_encode(["success" => true, "message" => "Settings saved successfully."]);
} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => $e->getMessage()]);
}
?>
