<?php
require_once '../includes/config.php';
require_once '../includes/device_security.php';
requireAdmin();
$db = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $a = $_POST['action'] ?? '';
    $db2 = getDB();
    if ($a === 'block')   { $db2->prepare("UPDATE user_devices SET is_blocked=1 WHERE id=?")->execute([intval($_POST['dev_id'])]); }
    if ($a === 'unblock') { $db2->prepare("UPDATE user_devices SET is_blocked=0 WHERE id=?")->execute([intval($_POST['dev_id'])]); }
    if ($a !== 'insert_test') { header('Location: device_debug.php?done=1'); exit; }
}


// Force create tables
initDeviceTables();

// Check tables exist
$tables = $db->query("SHOW TABLES LIKE 'user_devices'")->fetchAll();
$tableExists = count($tables) > 0;

// Count rows
$rowCount = 0;
if($tableExists) {
    $rowCount = $db->query("SELECT COUNT(*) FROM user_devices")->fetchColumn();
}

// All users
$users = $db->query("SELECT id,name,phone,email FROM users WHERE role!='admin' LIMIT 20")->fetchAll();

// Manual insert test
$msg = '';
if($_POST['action'] ?? '' === 'insert_test') {
    $uid = intval($_POST['uid']);
    $token = 'TEST_'.bin2hex(random_bytes(8));
    try {
        $db->prepare("INSERT INTO user_devices (user_id,device_token,device_name,browser,os,ip_address,is_active,is_blocked) VALUES (?,?,?,?,?,?,1,0)")
           ->execute([$uid,$token,'Test Device','Chrome','Android','127.0.0.1']);
        $msg = "✅ Test device inserted for user $uid";
    } catch(Exception $e) {
        $msg = "❌ Error: ".$e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Device Debug</title>
<link rel="stylesheet" href="../assets/css/admin.css">
</head>
<body>
<?php include '../includes/admin_sidebar.php'; ?>
<div class="main"><div class="content">
<h2>🔍 Device Debug</h2>

<?php if($msg): ?><div style="padding:12px;background:#f0fff4;border-radius:8px;margin:10px 0;font-weight:700"><?= $msg ?></div><?php endif; ?>

<div style="background:white;border-radius:12px;padding:20px;margin-bottom:16px">
    <h3>Table Status</h3>
    <p>user_devices table: <b style="color:<?= $tableExists?'green':'red' ?>"><?= $tableExists?'✅ EXISTS':'❌ NOT FOUND' ?></b></p>
    <p>Total device rows: <b><?= $rowCount ?></b></p>
</div>

<div style="background:white;border-radius:12px;padding:20px;margin-bottom:16px">
    <h3>Insert Test Device</h3>
    <form method="POST">
        <input type="hidden" name="action" value="insert_test">
        <select name="uid" style="padding:8px;margin-right:8px">
            <?php foreach($users as $u): ?>
            <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['name']) ?> (<?= $u['phone'] ?>)</option>
            <?php endforeach; ?>
        </select>
        <button type="submit" style="padding:8px 16px;background:#1a3c8f;color:white;border:none;border-radius:8px;cursor:pointer">Insert Test Device</button>
    </form>
</div>

<?php if($tableExists && $rowCount > 0): ?>
<div style="background:white;border-radius:12px;padding:20px">
    <h3>All Devices (<?= $rowCount ?>)</h3>
    <table style="width:100%;border-collapse:collapse;font-size:13px">
        <tr style="background:#f5f5f5"><th style="padding:8px;text-align:left">ID</th><th>User</th><th>Device</th><th>IP</th><th>Blocked</th><th>Action</th></tr>
        <?php
        $devs = $db->query("SELECT d.*,u.name FROM user_devices d JOIN users u ON d.user_id=u.id ORDER BY d.id DESC LIMIT 50")->fetchAll();
        foreach($devs as $d):
        ?>
        <tr style="border-bottom:1px solid #eee">
            <td style="padding:8px"><?= $d['id'] ?></td>
            <td style="padding:8px"><?= htmlspecialchars($d['name']) ?></td>
            <td style="padding:8px"><?= htmlspecialchars($d['device_name']??'—') ?></td>
            <td style="padding:8px"><?= $d['ip_address'] ?></td>
            <td style="padding:8px;color:<?= $d['is_blocked']?'red':'green' ?>"><?= $d['is_blocked']?'BLOCKED':'Active' ?></td>
            <td style="padding:8px">
                <form method="POST" style="display:inline">
                    <input type="hidden" name="action" value="<?= $d['is_blocked']?'unblock':'block' ?>">
                    <input type="hidden" name="dev_id" value="<?= $d['id'] ?>">
                    <button type="submit" style="padding:4px 10px;border:none;border-radius:6px;cursor:pointer;background:<?= $d['is_blocked']?'#f0fff4':'#fff5f5' ?>;color:<?= $d['is_blocked']?'green':'red' ?>"><?= $d['is_blocked']?'Unblock':'Block' ?></button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>
<?php endif; ?>

</div></div>
</body>
</html>
<?php /* This won't execute - handled above */ ?>
