<?php
/**
 * Update Per-Device SIM Preference
 * 
 * POST Parameters:
 *   - device_id (required)
 *   - preferred_sim (required): "sim1" or "sim2"
 * 
 * Auto-creates the preferred_sim column on first use.
 */
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

requireAuth();

// Accept both form-data and JSON
$rawInput = file_get_contents("php://input");
$inputJson = json_decode($rawInput, true);
$data = array_merge($_POST, is_array($inputJson) ? $inputJson : []);

$device_id = trim($data['device_id'] ?? '');
$preferred_sim = trim($data['preferred_sim'] ?? '');

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

if (!in_array($preferred_sim, ['sim1', 'sim2'])) {
    echo json_encode(['success' => false, 'message' => 'preferred_sim must be sim1 or sim2']);
    exit;
}

try {
    // Auto-create column if it doesn't exist (runs once, silent if already exists)
    try {
        $pdo->exec("ALTER TABLE devices ADD COLUMN preferred_sim VARCHAR(4) DEFAULT NULL");
    } catch (Exception $e) {
        // Column already exists — ignore
    }

    // Update the device's SIM preference
    $stmt = $pdo->prepare("UPDATE devices SET preferred_sim = ? WHERE device_id = ?");
    $stmt->execute([$preferred_sim, $device_id]);

    if ($stmt->rowCount() > 0) {
        echo json_encode([
            'success' => true,
            'message' => 'SIM preference updated to ' . strtoupper($preferred_sim),
            'device_id' => $device_id,
            'preferred_sim' => $preferred_sim
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Device not found']);
    }

} catch (Exception $e) {
    error_log("Update SIM error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
