<?php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

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");

require_once __DIR__ . '/../adminapi/includes/settings.php';
require_once __DIR__ . '/../adminapi/includes/response.php';
require_once __DIR__ . '/../adminapi/includes/micro_cache.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Response::error('Method not allowed', 405);
}

// ✅ 1-second cache to keep "instant" feel with 2s polling
$TTL = 1;
$device_id = $_GET['device_id'] ?? '';
$cacheKey = $device_id ? "getsettings:device:" . $device_id : "getsettings:global:v1";

$cached = mc_get($cacheKey);
if ($cached !== null && mc_age($cacheKey) < $TTL) {
    echo $cached;
    exit;
}

echo mc_lock($cacheKey, function() use ($cacheKey, $TTL, $device_id) {

    $cached2 = mc_get($cacheKey);
    if ($cached2 !== null && mc_age($cacheKey) < $TTL) {
        return $cached2;
    }

    try {
        $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);

        // Check for per-device SIM preference
        $simSlot = $settings['preferred_sim_slot'] ?? 'sim1';
        if ($device_id !== '') {
            try {
                global $pdo;
                if (!isset($pdo)) {
                    require_once __DIR__ . '/../adminapi/includes/db.php';
                }
                $simStmt = $pdo->prepare("SELECT preferred_sim FROM devices WHERE device_id = ? LIMIT 1");
                $simStmt->execute([$device_id]);
                $simRow = $simStmt->fetch(PDO::FETCH_ASSOC);
                if ($simRow && !empty($simRow['preferred_sim'])) {
                    $simSlot = $simRow['preferred_sim'];
                }
            } catch (Exception $e) {
                // Column might not exist yet, use global
            }
        }

        // Keep same response keys your app/admin may rely on
        $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'] ?? '',
            'preferred_sim_slot' => $simSlot,
            'updatedate' => $settings['updatedate'] ?? date('Y-m-d H:i:s'),
            'last_modified' => $lastModifiedFormatted,
            'etag' => $etag
        ];

        $json = json_encode(array_merge(['success' => true], $response));

        // Mild cache headers (won't hurt Android)
        header("Cache-Control: private, max-age=1");

        mc_set($cacheKey, $json, $TTL);
        return $json;

    } catch (Throwable $e) {
        http_response_code(500);
        return json_encode(['success'=>false,'error'=>'Error fetching settings']);
    }
});
