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

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $name = sanitize($_POST['name']);
        $op = intval($_POST['operator_id']);
        $pkg = intval($_POST['package_id']);
        $schedule = sanitize($_POST['schedule_type']);
        $time = sanitize($_POST['schedule_time']);
        $price = floatval($_POST['price']);
        $desc = sanitize($_POST['description']);
        $db->prepare("INSERT INTO drive_templates (name,operator_id,package_id,schedule_type,schedule_time,price,description) VALUES (?,?,?,?,?,?,?)")
           ->execute([$name,$op,$pkg,$schedule,$time,$price,$desc]);
    } elseif ($action === 'toggle') {
        $id = intval($_POST['id']);
        $db->prepare("UPDATE drive_templates SET status = CASE WHEN status='active' THEN 'inactive' ELSE 'active' END WHERE id=?")->execute([$id]);
    } elseif ($action === 'delete') {
        $id = intval($_POST['id']);
        $db->prepare("DELETE FROM drive_templates WHERE id=?")->execute([$id]);
    }
    header('Location: drive.php'); exit;
}

$templates = $db->query("SELECT dt.*, o.name as op_name, p.name as pkg_name, p.sell_price,
    (SELECT COUNT(*) FROM drive_subscriptions ds WHERE ds.template_id=dt.id AND ds.status='active') as subscribers
    FROM drive_templates dt
    JOIN operators o ON dt.operator_id=o.id
    JOIN packages p ON dt.package_id=p.id
    ORDER BY dt.created_at DESC")->fetchAll();

$operators = $db->query("SELECT * FROM operators WHERE status='active'")->fetchAll();
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drive Management - Admin</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../assets/css/admin.css">
</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>
            <h1><i class="fas fa-bolt"></i> Drive Plan Management</h1>
        </div>
        <div class="topbar-right">
            <button class="btn-add" onclick="document.getElementById('addModal').classList.add('open')">
            <i class="fas fa-plus"></i> নতুন Drive Plan
        </button>
        </div>
    </div>

    <div class="content">
        <?php if (empty($templates)): ?>
        <div class="empty">
            <i class="fas fa-bolt"></i>
            এখনো কোনো Drive Plan তৈরি হয়নি<br>
            <small>উপরে "নতুন Drive Plan" বাটনে ক্লিক করুন</small>
        </div>
        <?php else: ?>
        <div class="grid">
            <?php foreach ($templates as $t): ?>
            <div class="drive-card">
                <div class="drive-card-header">
                    <div class="drive-name"><?= htmlspecialchars($t['name']) ?></div>
                    <span class="badge badge-<?= $t['status'] ?>"><?= $t['status']==='active'?'সক্রিয়':'বন্ধ' ?></span>
                </div>
                <div class="drive-price"><?= CURRENCY ?><?= number_format($t['price'],2) ?></div>
                <div class="drive-details">
                    <div class="detail-row"><i class="fas fa-sim-card"></i> <?= $t['op_name'] ?></div>
                    <div class="detail-row"><i class="fas fa-box"></i> <?= $t['pkg_name'] ?></div>
                    <div class="detail-row"><i class="fas fa-clock"></i> <?= ucfirst($t['schedule_type']) ?><?= $t['schedule_time']?' - '.$t['schedule_time']:'' ?></div>
                    <?php if ($t['description']): ?>
                    <div class="detail-row"><i class="fas fa-info-circle"></i> <?= htmlspecialchars($t['description']) ?></div>
                    <?php endif; ?>
                </div>
                <div class="subscribers"><i class="fas fa-users"></i> <?= $t['subscribers'] ?> জন সাবস্ক্রাইব করেছে</div>
                <div class="card-actions">
                    <form method="POST" style="flex:1">
                        <input type="hidden" name="action" value="toggle">
                        <input type="hidden" name="id" value="<?= $t['id'] ?>">
                        <button type="submit" class="btn-sm <?= $t['status']==='active'?'btn-toggle-on':'btn-toggle-off' ?>" style="width:100%">
                            <i class="fas fa-<?= $t['status']==='active'?'pause':'play' ?>"></i>
                            <?= $t['status']==='active'?'বন্ধ করুন':'চালু করুন' ?>
                        </button>
                    </form>
                    <form method="POST">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?= $t['id'] ?>">
                        <button type="submit" class="btn-sm btn-delete" onclick="return confirm('এই plan মুছবেন?')">
                            <i class="fas fa-trash"></i>
                        </button>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Add Modal -->
<div class="modal" id="addModal">
    <div class="modal-box">
        <h3><i class="fas fa-plus-circle"></i> নতুন Drive Plan তৈরি করুন</h3>
        <form method="POST">
            <input type="hidden" name="action" value="add">
            <div class="form-group">
                <label>Plan এর নাম</label>
                <input type="text" name="name" placeholder="যেমন: GP Daily 1GB" required>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>অপারেটর</label>
                    <select name="operator_id" onchange="loadPkgs(this.value)" required>
                        <option value="">বেছে নিন</option>
                        <?php foreach ($operators as $o): ?>
                        <option value="<?= $o['id'] ?>"><?= $o['name'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>প্যাকেজ</label>
                    <select name="package_id" id="pkgSelect" required>
                        <option value="">আগে অপারেটর বেছে নিন</option>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>শিডিউল</label>
                    <select name="schedule_type" required>
                        <option value="daily">প্রতিদিন</option>
                        <option value="weekly">সাপ্তাহিক</option>
                        <option value="monthly">মাসিক</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>সময়</label>
                    <input type="time" name="schedule_time">
                </div>
            </div>
            <div class="form-group">
                <label>মূল্য (৳)</label>
                <input type="number" name="price" placeholder="0.00" step="0.01" required>
            </div>
            <div class="form-group">
                <label>বিবরণ (ঐচ্ছিক)</label>
                <textarea name="description" rows="2" placeholder="Plan সম্পর্কে বিস্তারিত..."></textarea>
            </div>
            <div class="modal-actions">
                <button type="submit" class="btn-submit"><i class="fas fa-save"></i> সেভ করুন</button>
                <button type="button" class="btn-cancel" onclick="document.getElementById('addModal').classList.remove('open')">বাতিল</button>
            </div>
        </form>
    </div>
</div>

<script>
function loadPkgs(opId) {
    fetch('../api/packages.php?operator_id=' + opId)
        .then(r => r.json())
        .then(d => {
            const sel = document.getElementById('pkgSelect');
            sel.innerHTML = '<option value="">প্যাকেজ বেছে নিন</option>';
            d.packages.forEach(p => {
                sel.innerHTML += `<option value="${p.id}">${p.name} - ৳${p.sell_price}</option>`;
            });
        });
}
</script>
</body>
</html>
