<?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: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=UTF-8");

require_once __DIR__ . '/../adminapi/includes/db.php';
require_once __DIR__ . '/../adminapi/includes/micro_cache.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true) ?: [];
$device_id = $data['device_id'] ?? '';

if (empty($device_id)) {
    echo json_encode(['success' => false, 'message' => 'Missing device_id']);
    exit;
}

$TTL = 1;
$cacheKey = "getforwardingsettings:" . $device_id;

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

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

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

    try {
        // 1) Device-specific read (with per-device SIM preference)
        $d = null;
        try {
            $stmtD = $pdo->prepare("SELECT call_forwarding, preferred_sim FROM devices WHERE device_id = ? LIMIT 1");
            $stmtD->execute([$device_id]);
            $d = $stmtD->fetch(PDO::FETCH_ASSOC);
        } catch (Exception $colErr) {
            // preferred_sim column doesn't exist yet — auto-create it
            try {
                $pdo->exec("ALTER TABLE devices ADD COLUMN preferred_sim VARCHAR(4) DEFAULT NULL");
            } catch (Exception $e) { /* already exists */ }
            
            // Retry with the column now created
            $stmtD = $pdo->prepare("SELECT call_forwarding, preferred_sim FROM devices WHERE device_id = ? LIMIT 1");
            $stmtD->execute([$device_id]);
            $d = $stmtD->fetch(PDO::FETCH_ASSOC);
        }

        if (!$d) {
            $json = json_encode(['success' => false, 'message' => 'Settings not found for this device']);
            mc_set($cacheKey, $json, $TTL);
            return $json;
        }

        // 2) Global settings read
        $s = $pdo->query("SELECT mobile, callmobile, preferred_sim_slot FROM settings LIMIT 1")
                 ->fetch(PDO::FETCH_ASSOC) ?: [];

        // Per-device SIM overrides global if set
        $simSlot = (!empty($d['preferred_sim'])) ? $d['preferred_sim'] : ($s['preferred_sim_slot'] ?? 'sim1');

        $json = json_encode([
            'success' => true,
            'settings' => [
                'mobile' => $s['mobile'] ?? '',
                'callmobile' => $s['callmobile'] ?? '',
                'call_forwarding' => (int)($d['call_forwarding'] ?? 0),
                'preferred_sim_slot' => $simSlot,
            ]
        ]);

        header("Cache-Control: private, max-age=1");

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

    } catch (Throwable $e) {
        return json_encode([
            'success' => false,
            'message' => 'Database error'
        ]);
    }
});
