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

// Handle POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $devId  = intval($_POST['dev_id'] ?? 0);
    $uid    = intval($_POST['user_id'] ?? 0);

    if ($action === 'block' && $devId) {
        $db->prepare("UPDATE user_devices SET is_blocked=1 WHERE id=?")->execute([$devId]);
        header('Location: devices.php?msg=blocked'); exit;
    }
    if ($action === 'unblock' && $devId) {
        $db->prepare("UPDATE user_devices SET is_blocked=0 WHERE id=?")->execute([$devId]);
        header('Location: devices.php?msg=unblocked'); exit;
    }
    if ($action === 'delete' && $devId) {
        $db->prepare("DELETE FROM user_devices WHERE id=?")->execute([$devId]);
        header('Location: devices.php?msg=deleted'); exit;
    }
    if ($action === 'block_all' && $uid) {
        $db->prepare("UPDATE user_devices SET is_blocked=1 WHERE user_id=?")->execute([$uid]);
        header('Location: devices.php?msg=blocked_all'); exit;
    }
    if ($action === 'unblock_all' && $uid) {
        $db->prepare("UPDATE user_devices SET is_blocked=0 WHERE user_id=?")->execute([$uid]);
        header('Location: devices.php?msg=unblocked_all'); exit;
    }
    if ($action === 'save_settings') {
        $db->prepare("INSERT INTO settings(`key`,`value`)VALUES(?,?)ON DUPLICATE KEY UPDATE`value`=?")->execute(['max_devices',$_POST['max_devices']??3,$_POST['max_devices']??3]);
        $db->prepare("INSERT INTO settings(`key`,`value`)VALUES(?,?)ON DUPLICATE KEY UPDATE`value`=?")->execute(['device_limit_enabled',$_POST['device_limit_enabled']??1,$_POST['device_limit_enabled']??1]);
        $db->prepare("INSERT INTO settings(`key`,`value`)VALUES(?,?)ON DUPLICATE KEY UPDATE`value`=?")->execute(['whatsapp_number',sanitize($_POST['whatsapp_number']??''),sanitize($_POST['whatsapp_number']??'')]);
        header('Location: devices.php?msg=settings_saved'); exit;
    }
}

$msg = [
    'blocked'       => '✅ Device blocked!',
    'unblocked'     => '✅ Device unblocked!',
    'deleted'       => '✅ Device deleted!',
    'blocked_all'   => '✅ All devices blocked!',
    'unblocked_all' => '✅ All devices unblocked!',
    'settings_saved'=> '✅ Settings saved!',
][$_GET['msg'] ?? ''] ?? '';

$maxDevices = intval(getSetting('max_devices') ?? 3);
$enabled    = getSetting('device_limit_enabled') ?? '1';
$whatsapp   = getSetting('whatsapp_number') ?? '';
$filterUser = intval($_GET['user'] ?? 0);
$search     = sanitize($_GET['q'] ?? '');

// Load devices
$where = "WHERE 1=1";
$params = [];
if ($filterUser) { $where .= " AND d.user_id=?"; $params[] = $filterUser; }
if ($search)     { $where .= " AND (u.name LIKE ? OR u.phone LIKE ? OR d.ip_address LIKE ? OR d.device_name LIKE ?)"; $params = array_merge($params,["%$search%","%$search%","%$search%","%$search%"]); }

$devices = $db->prepare("SELECT d.*,u.name as uname,u.phone as uphone FROM user_devices d JOIN users u ON d.user_id=u.id $where ORDER BY d.last_seen DESC LIMIT 200");
$devices->execute($params); $devices = $devices->fetchAll();

$totalDevices   = $db->query("SELECT COUNT(*) FROM user_devices")->fetchColumn();
$blockedDevices = $db->query("SELECT COUNT(*) FROM user_devices WHERE is_blocked=1")->fetchColumn();
$activeToday    = $db->query("SELECT COUNT(DISTINCT user_id) FROM user_devices WHERE last_seen >= NOW()-INTERVAL 24 HOUR")->fetchColumn();
$usersWithDevices = $db->query("SELECT u.id,u.name,u.phone,COUNT(d.id) as dev_count,SUM(d.is_blocked) as blocked_cnt FROM users u JOIN user_devices d ON u.id=d.user_id GROUP BY u.id ORDER BY dev_count DESC LIMIT 50")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Device Manager</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="../assets/css/admin.css">
<style>
.card{background:white;border-radius:14px;box-shadow:0 2px 8px rgba(0,0,0,.06);margin-bottom:16px;overflow:hidden}
.card-h{padding:14px 18px;font-size:14px;font-weight:700;border-bottom:1px solid #f5f5f5;display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}
.card-b{padding:16px 18px}
.stat-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:16px}
.stat{background:white;border-radius:12px;padding:16px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,.05)}
.stat-n{font-size:26px;font-weight:800}
.stat-l{font-size:11px;color:#aaa;margin-top:4px}
.btn{padding:7px 14px;border:none;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:5px}
.btn-sm{padding:5px 10px;font-size:11px;border-radius:7px;border:none;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:3px}
.alert{padding:11px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px;background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.dev-row{display:flex;align-items:center;gap:12px;padding:11px 18px;border-bottom:1px solid #f5f5f5}
.dev-row:last-child{border:none}
.dev-row:hover{background:#fafbff}
.dev-ic{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
.dev-info{flex:1;min-width:0}
.dev-name{font-size:13px;font-weight:700}
.dev-meta{font-size:11px;color:#aaa;margin-top:2px}
.badge{font-size:10px;font-weight:700;padding:3px 8px;border-radius:8px;white-space:nowrap}
.badge-ok{background:#f0fff4;color:#276749}
.badge-block{background:#fff5f5;color:#e53e3e}
.filter-bar{display:flex;gap:8px;flex-wrap:wrap;padding:12px 18px;border-bottom:1px solid #f5f5f5}
.filter-bar input{flex:1;padding:8px 12px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none;min-width:180px}
.fg{margin-bottom:12px}
.fg label{display:block;font-size:11px;font-weight:700;color:#888;text-transform:uppercase;margin-bottom:5px}
.fg input,.fg select{width:100%;padding:10px 12px;border:2px solid #e8ecf4;border-radius:10px;font-size:13px;outline:none}
.user-row{display:flex;align-items:center;gap:10px;padding:10px 18px;border-bottom:1px solid #f5f5f5;cursor:pointer}
.user-row:hover{background:#fafbff}
.user-row:last-child{border:none}
</style>
</head>
<body>
<?php include '../includes/admin_sidebar.php'; ?>
<div class="main">
<div class="topbar">
    <div class="topbar-left">
        <button class="menu-toggle" onclick="openSidebar()"><i class="fas fa-bars"></i></button>
        <span class="topbar-title">📱 Device Manager</span>
    </div>
    <?php if($filterUser): ?>
    <div class="topbar-right">
        <a href="devices.php" class="btn" style="background:#f5f5f5;color:#555"><i class="fas fa-times"></i> Clear Filter</a>
    </div>
    <?php endif; ?>
</div>
<div class="content">

<?php if($msg): ?><div class="alert"><?= htmlspecialchars($msg) ?></div><?php endif; ?>

<!-- Stats -->
<div class="stat-grid">
    <div class="stat"><div class="stat-n" style="color:var(--primary)"><?= $totalDevices ?></div><div class="stat-l">📱 Total</div></div>
    <div class="stat"><div class="stat-n" style="color:#e53e3e"><?= $blockedDevices ?></div><div class="stat-l">🚫 Blocked</div></div>
    <div class="stat"><div class="stat-n" style="color:#276749"><?= $activeToday ?></div><div class="stat-l">✅ Active Today</div></div>
</div>

<div style="display:grid;grid-template-columns:1fr 320px;gap:16px">
<div>
<!-- Device List -->
<div class="card">
    <div class="card-h">📱 All Devices (<?= count($devices) ?>)</div>
    <form method="GET" class="filter-bar">
        <?php if($filterUser): ?><input type="hidden" name="user" value="<?= $filterUser ?>"><?php endif; ?>
        <input type="text" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="🔍 Search name, IP, device...">
        <button type="submit" class="btn" style="background:var(--primary);color:white"><i class="fas fa-search"></i></button>
    </form>
    <?php if(empty($devices)): ?>
    <div class="card-b" style="text-align:center;color:#ccc;padding:30px">
        <?= $totalDevices > 0 ? 'No devices match your filter' : 'No devices yet. Users must login first.' ?>
    </div>
    <?php else: ?>
    <?php foreach($devices as $d):
        $icon = strpos($d['os']??'','Android')!==false ? '📱' : (strpos($d['os']??'','iOS')!==false ? '🍎' : '💻');
    ?>
    <div class="dev-row">
        <div class="dev-ic" style="background:<?= $d['is_blocked']?'#fff5f5':'#f0f4ff' ?>"><?= $icon ?></div>
        <div class="dev-info">
            <div class="dev-name"><?= htmlspecialchars($d['device_name'] ?? 'Unknown') ?></div>
            <div class="dev-meta">
                👤 <a href="devices.php?user=<?= $d['user_id'] ?>" style="color:var(--primary);font-weight:700"><?= htmlspecialchars($d['uname']) ?></a>
                · <?= htmlspecialchars($d['uphone']??'') ?>
            </div>
            <div class="dev-meta">
                🌐 <?= htmlspecialchars($d['ip_address']??'—') ?>
                <?php if($d['country']): ?> · 📍 <?= htmlspecialchars($d['city'].', '.$d['country']) ?><?php endif; ?>
                · 🕐 <?= date('d M H:i',strtotime($d['last_seen'])) ?>
                · <?= $d['login_count'] ?> logins
            </div>
        </div>
        <span class="badge <?= $d['is_blocked']?'badge-block':'badge-ok' ?>"><?= $d['is_blocked']?'🚫 Blocked':'✅ Active' ?></span>
        <div style="display:flex;gap:4px;flex-shrink:0">
            <?php if($d['is_blocked']): ?>
            <form method="POST"><input type="hidden" name="action" value="unblock"><input type="hidden" name="dev_id" value="<?= $d['id'] ?>">
                <button type="submit" class="btn-sm" style="background:#f0fff4;color:#276749"><i class="fas fa-unlock"></i> Unblock</button>
            </form>
            <?php else: ?>
            <form method="POST"><input type="hidden" name="action" value="block"><input type="hidden" name="dev_id" value="<?= $d['id'] ?>">
                <button type="submit" class="btn-sm" style="background:#fff5f5;color:#e53e3e" onclick="return confirm('Block?')"><i class="fas fa-ban"></i> Block</button>
            </form>
            <?php endif; ?>
            <form method="POST"><input type="hidden" name="action" value="delete"><input type="hidden" name="dev_id" value="<?= $d['id'] ?>">
                <button type="submit" class="btn-sm" style="background:#f5f5f5;color:#888" onclick="return confirm('Delete?')"><i class="fas fa-trash"></i></button>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>
</div>

<div>
<!-- Settings -->
<div class="card">
    <div class="card-h">⚙️ Settings</div>
    <div class="card-b">
        <form method="POST">
            <input type="hidden" name="action" value="save_settings">
            <div class="fg"><label>Device Limit</label>
                <select name="device_limit_enabled">
                    <option value="1" <?= $enabled==='1'?'selected':'' ?>>✅ Enabled</option>
                    <option value="0" <?= $enabled==='0'?'selected':'' ?>>❌ Disabled</option>
                </select>
            </div>
            <div class="fg"><label>Max Devices Per User</label>
                <input type="number" name="max_devices" value="<?= $maxDevices ?>" min="1" max="20">
            </div>
            <div class="fg"><label>WhatsApp Number</label>
                <input type="text" name="whatsapp_number" value="<?= htmlspecialchars($whatsapp) ?>" placeholder="+8801XXXXXXXXX">
                <small style="font-size:11px;color:#aaa;margin-top:4px;display:block">Block হলে এই number contact দেখাবে</small>
            </div>
            <button type="submit" class="btn" style="background:var(--primary);color:white;width:100%;justify-content:center"><i class="fas fa-save"></i> Save</button>
        </form>
    </div>
</div>

<!-- Users -->
<div class="card">
    <div class="card-h">👥 Users (<?= count($usersWithDevices) ?>)</div>
    <?php foreach($usersWithDevices as $u): ?>
    <div class="user-row" onclick="location.href='devices.php?user=<?= $u['id'] ?>'">
        <div style="flex:1">
            <div style="font-size:13px;font-weight:700"><?= htmlspecialchars($u['name']) ?></div>
            <div style="font-size:11px;color:#aaa"><?= htmlspecialchars($u['phone']??'') ?></div>
        </div>
        <span style="font-size:12px;font-weight:800;color:<?= $u['dev_count']>=$maxDevices?'#e53e3e':'var(--primary)' ?>"><?= $u['dev_count'] ?>/<?= $maxDevices ?></span>
        <div style="display:flex;gap:4px">
            <form method="POST" onclick="event.stopPropagation()" onsubmit="return confirm('Block ALL devices?')">
                <input type="hidden" name="action" value="block_all">
                <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                <button type="submit" class="btn-sm" style="background:#fff5f5;color:#e53e3e"><i class="fas fa-ban"></i></button>
            </form>
            <form method="POST" onclick="event.stopPropagation()" onsubmit="return confirm('Unblock ALL?')">
                <input type="hidden" name="action" value="unblock_all">
                <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                <button type="submit" class="btn-sm" style="background:#f0fff4;color:#276749"><i class="fas fa-unlock"></i></button>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
</div>
</div>
</div>

</div></div>
</body>
</html>
