<?php
session_start();
require_once __DIR__ . '/../../../dripend/includes/db.php';
// Ensure the request is POST and return JSON for the AJAX call
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize Inputs
    $enable_api_sync = isset($_POST['enable_api_sync']) && $_POST['enable_api_sync'] == '1' ? 1 : 0;
    $api_endpoint = mysqli_real_escape_string($conn, $_POST['api_endpoint'] ?? '');
    $api_username = mysqli_real_escape_string($conn, $_POST['api_username'] ?? '');
    $api_token = mysqli_real_escape_string($conn, $_POST['api_token'] ?? '');

    // Update only the API fields in the database
    $update_sql = "UPDATE nhis_setup SET 
                   enable_api_sync = $enable_api_sync,
                   api_endpoint = '$api_endpoint',
                   api_username = '$api_username',
                   api_token = '$api_token' 
                   WHERE id = 1";

    if (mysqli_query($conn, $update_sql)) {
        echo json_encode(['status' => 'success', 'message' => 'API Credentials updated successfully.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . mysqli_error($conn)]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>