<?php
session_start();
include 'include.php';

$result = array();
$result['error'] = 1;
$result['error_msg'] = "Something went wrong";

if (isset($_POST['updte']) && $_POST['updte'] == 1) {
    $settings_id = isset($_POST['settings_id']) ? intval($_POST['settings_id']) : 0;
    $api_key = isset($_POST['api_key']) ? trim($_POST['api_key']) : '';
    $sender_id = isset($_POST['sender_id']) ? trim($_POST['sender_id']) : '';
    $default_footer = isset($_POST['default_footer']) ? trim($_POST['default_footer']) : '';

    if (empty($api_key) || empty($sender_id)) {
        $result['error'] = 1;
        $result['error_msg'] = "API Key and Sender ID are required";
        echo json_encode($result);
        exit;
    }

    // Connect to database
    $con = connect_database();

    // Sanitize inputs
    $api_key = mysqli_real_escape_string($con, $api_key);
    $sender_id = mysqli_real_escape_string($con, $sender_id);
    $default_footer = mysqli_real_escape_string($con, $default_footer);

    if ($settings_id > 0) {
        // Update existing settings
        $sql = "UPDATE whatsapp_settings SET
                api_key = '$api_key',
                sender_id = '$sender_id',
                default_footer = '$default_footer',
                updated_at = NOW()
                WHERE id = $settings_id";

        if (mysqli_query($con, $sql)) {
            $result['error'] = 0;
            $result['error_msg'] = "WhatsApp settings updated successfully!";
            $result['settings_id'] = $settings_id;
        } else {
            $result['error'] = 1;
            $result['error_msg'] = "Failed to update settings: " . mysqli_error($con);
        }
    } else {
        // Deactivate all existing settings first
        mysqli_query($con, "UPDATE whatsapp_settings SET is_active = 0");

        // Insert new settings
        $sql = "INSERT INTO whatsapp_settings (api_key, sender_id, default_footer, is_active, created_at, updated_at)
                VALUES ('$api_key', '$sender_id', '$default_footer', 1, NOW(), NOW())";

        if (mysqli_query($con, $sql)) {
            $result['error'] = 0;
            $result['error_msg'] = "WhatsApp settings saved successfully!";
            $result['settings_id'] = mysqli_insert_id($con);
        } else {
            $result['error'] = 1;
            $result['error_msg'] = "Failed to save settings: " . mysqli_error($con);
        }
    }

    $con->close();
} else {
    $result['error'] = 1;
    $result['error_msg'] = "Invalid request";
}

echo json_encode($result);
?>
