<?php
session_start();
if (!isset($_SESSION['unohs'])) { header("Location: index.php"); exit(); }
include "conn.php";

$message = '';

// ✅ Random, Secure Secret তৈরি করার Function
function generateSecret($length = 32) {
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $secret = '';
    for ($i = 0; $i < $length; $i++) {
        $secret .= $chars[random_int(0, strlen($chars) - 1)];
    }
    return $secret;
}

// ✅ নতুন Device যোগ করা
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $deviceName = trim($_POST['device_name']);
    $newSecret = generateSecret();

    if ($deviceName !== '') {
        $stmt = $conn->prepare("INSERT INTO sms_app_devices (device_name, api_secret) VALUES (?, ?)");
        $stmt->bind_param("ss", $deviceName, $newSecret);
        if ($stmt->execute()) {
            $message = "✅ নতুন Device যোগ হয়েছে। নিচে থেকে Secret Copy করে App-এ বসাও।";
        }
        $stmt->close();
    }
}

// ✅ Device Active/Inactive করা
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'toggle') {
    $deviceId = intval($_POST['device_id']);
    $newStatus = intval($_POST['new_status']);
    $stmt = $conn->prepare("UPDATE sms_app_devices SET is_active = ? WHERE id = ?");
    $stmt->bind_param("ii", $newStatus, $deviceId);
    $stmt->execute();
    $stmt->close();
    $message = "✅ Device Status বদলানো হয়েছে।";
}

// ✅ সব Device দেখানো
$devices = [];
$result = $conn->query("SELECT * FROM sms_app_devices ORDER BY id DESC");
while ($row = $result->fetch_assoc()) { $devices[] = $row; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SMS Device Manager - RAJ365 Admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { background: #0A0A0A; color: #F5EFDC; font-family: sans-serif; padding: 20px; }
        .card { background: #171512; border: 1px solid #3A3226; border-radius: 14px; padding: 18px; margin-bottom: 16px; }
        input { background: #0A0A0A; border: 1px solid #3A3226; color: #F5EFDC; border-radius: 8px; padding: 10px 14px; width: 100%; margin-bottom: 10px; }
        button { border: none; border-radius: 8px; padding: 10px 16px; font-weight: 700; cursor: pointer; }
        .device-row { background: #0A0A0A; border: 1px solid #241C42; border-radius: 10px; padding: 14px; margin-bottom: 10px; }
        .secret-box { background: #171512; border: 1px dashed #D4AF37; border-radius: 8px; padding: 10px; font-family: monospace; font-size: 12.5px; color: #D4AF37; word-break: break-all; margin-top: 8px; user-select: all; }
        .badge-active { background: rgba(31,185,121,.15); color: #1FB979; padding: 3px 10px; border-radius: 999px; font-size: 11px; font-weight: 700; }
        .badge-inactive { background: rgba(232,50,60,.15); color: #E8323C; padding: 3px 10px; border-radius: 999px; font-size: 11px; font-weight: 700; }
    </style>
</head>
<body>
<div style="max-width:600px; margin:0 auto;">
    <h3 style="color:#D4AF37;">📱 SMS Device Manager</h3>
    <p style="color:#8A8270; font-size:12.5px;">এখান থেকেই নতুন Device Secret তৈরি করো — SQL চালানোর দরকার নেই।</p>

    <?php if ($message): ?>
        <div class="card" style="border-color:#D4AF37;"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <div class="card">
        <h5 style="color:#D4AF37; margin-bottom:12px;">➕ নতুন Device যোগ করো</h5>
        <form method="POST">
            <input type="hidden" name="action" value="add">
            <input type="text" name="device_name" placeholder="Device-এর নাম (যেমন: Main Phone)" required>
            <button type="submit" style="background:#D4AF37; color:#1A1400; width:100%;">Secret তৈরি করো</button>
        </form>
    </div>

    <div class="card">
        <h5 style="color:#D4AF37; margin-bottom:12px;">📋 বর্তমান সব Device</h5>
        <?php if (empty($devices)): ?>
            <p style="color:#8A8270;">এখনো কোনো Device যোগ করা হয়নি।</p>
        <?php else: ?>
            <?php foreach ($devices as $d): ?>
                <div class="device-row">
                    <div style="display:flex; justify-content:space-between; align-items:center;">
                        <b><?= htmlspecialchars($d['device_name']) ?></b>
                        <span class="<?= $d['is_active'] ? 'badge-active' : 'badge-inactive' ?>">
                            <?= $d['is_active'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </div>
                    <div class="secret-box"><?= htmlspecialchars($d['api_secret']) ?></div>
                    <p style="color:#4A4438; font-size:11px; margin-top:6px;">
                        শেষ দেখা গেছে: <?= $d['last_seen'] ?? 'কখনো না' ?>
                    </p>
                    <form method="POST" style="margin-top:8px;">
                        <input type="hidden" name="action" value="toggle">
                        <input type="hidden" name="device_id" value="<?= $d['id'] ?>">
                        <input type="hidden" name="new_status" value="<?= $d['is_active'] ? 0 : 1 ?>">
                        <button type="submit" style="background:<?= $d['is_active'] ? '#E8323C' : '#1FB979' ?>; color:#fff; width:100%;">
                            <?= $d['is_active'] ? 'Deactivate করো' : 'Activate করো' ?>
                        </button>
                    </form>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <a href="dashboard.php" style="color:#D4AF37;">← Dashboard-এ ফিরে যাও</a>
</div>
</body>
</html>
