<?php
// Allow cross-origin requests
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=UTF-8");

// Optional: respond early to preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Only allow GET
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405); // Method Not Allowed
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Include settings class
require_once '../includes/settings.php';

try {
    // Fetch settings from DB
    $settingsObj = new Settings();
    $settings = $settingsObj->getAllSettings();

    $mobile = $settings['mobile'] ?? '';
    $lastModified = isset($settings['updatedate']) && !empty($settings['updatedate'])
        ? strtotime($settings['updatedate'])
        : time();
    $lastModifiedFormatted = gmdate('D, d M Y H:i:s', $lastModified) . ' GMT';
    $etag = md5($mobile . $lastModified);

    // Headers for cache validation
    header("Last-Modified: $lastModifiedFormatted");
    header("ETag: \"$etag\"");
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Pragma: no-cache");

    // Client cache check
    $clientEtag = $_SERVER['HTTP_IF_NONE_MATCH'] ?? '';
    $clientLastModified = $_SERVER['HTTP_IF_MODIFIED_SINCE'] ?? '';

    if ($clientEtag === "\"$etag\"" || $clientLastModified === $lastModifiedFormatted) {
        http_response_code(304); // Not Modified
        exit;
    }

    // Build response
    $response = [
        'id' => $settings['id'] ?? 1,
        'mobile' => $mobile,
        'title' => $settings['title'] ?? '',
        'callmobile' => $settings['callmobile'] ?? '',
        'call_forwarding' => isset($settings['call_forwarding']) ? (int)$settings['call_forwarding'] : 0,
        'subheading' => $settings['subheading'] ?? '',
        'upload' => $settings['upload'] ?? '',
        'image1' => $settings['image1'] ?? '',
        'image2' => $settings['image2'] ?? '',
        'image3' => $settings['image3'] ?? '',
        'updatedate' => $settings['updatedate'] ?? date('Y-m-d H:i:s'),
        'last_modified' => $lastModifiedFormatted,
        'etag' => $etag,
        'success' => true
    ];

    // Send JSON
    echo json_encode($response);

} catch (Exception $e) {
    http_response_code(500); // Internal Server Error
    echo json_encode([
        'error' => 'An error occurred while fetching settings',
        'message' => $e->getMessage()
    ]);
}
?>
