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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'add' || $action === 'edit') {
        $id             = intval($_POST['id'] ?? 0);
        $operator_id    = intval($_POST['operator_id']);
        $name           = sanitize($_POST['name']);
        $type           = sanitize($_POST['type']);
        $amount         = floatval($_POST['amount']);
        $validity       = sanitize($_POST['validity']);
        $description    = sanitize($_POST['description']);
        $cost_price     = floatval($_POST['cost_price']);
        $sell_price     = floatval($_POST['sell_price']);
        $reseller_price = floatval($_POST['reseller_price'] ?? $sell_price);
        $status         = sanitize($_POST['status'] ?? 'active');
        if ($action === 'add') {
            $db->prepare("INSERT INTO packages (operator_id,name,type,amount,validity,description,cost_price,sell_price,reseller_price,status) VALUES (?,?,?,?,?,?,?,?,?,?)")
               ->execute([$operator_id,$name,$type,$amount,$validity,$description,$cost_price,$sell_price,$reseller_price,$status]);
            $_SESSION['flash'] = ['type'=>'success','msg'=>'✅ প্যাকেজ যোগ হয়েছে!'];
        } else {
            $db->prepare("UPDATE packages SET operator_id=?,name=?,type=?,amount=?,validity=?,description=?,cost_price=?,sell_price=?,reseller_price=?,status=? WHERE id=?")
               ->execute([$operator_id,$name,$type,$amount,$validity,$description,$cost_price,$sell_price,$reseller_price,$status,$id]);
            $_SESSION['flash'] = ['type'=>'success','msg'=>'✅ আপডেট হয়েছে!'];
        }
    } elseif ($action === 'toggle') {
        $db->prepare("UPDATE packages SET status = CASE WHEN status='active' THEN 'inactive' ELSE 'active' END WHERE id=?")->execute([intval($_POST['id'])]);
    } elseif ($action === 'delete') {
        $db->prepare("DELETE FROM packages WHERE id=?")->execute([intval($_POST['id'])]);
        $_SESSION['flash'] = ['type'=>'warning','msg'=>'মুছে দেওয়া হয়েছে।'];
    }
    header('Location: packages.php'); exit;
}

$flash      = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);
$operators  = $db->query("SELECT * FROM operators ORDER BY id")->fetchAll();
$filterOp   = intval($_GET['op']   ?? 0);
$filterType = sanitize($_GET['type'] ?? '');
$where = "WHERE 1=1"; $params = [];
if ($filterOp)   { $where .= " AND p.operator_id=?"; $params[] = $filterOp; }
if ($filterType) { $where .= " AND p.type=?";         $params[] = $filterType; }
$stmt = $db->prepare("SELECT p.*, o.name as op_name FROM packages p JOIN operators o ON p.operator_id=o.id $where ORDER BY p.operator_id, p.type, p.amount");
$stmt->execute($params);
$packages = $stmt->fetchAll();
$typeLabels = ['topup'=>'💰 Topup','data'=>'📶 Data','voice'=>'📞 Voice','sms'=>'💬 SMS','combo'=>'🎁 Combo','drive'=>'⚡ Drive'];
$typeColors = ['topup'=>'#e53e3e','data'=>'#3182ce','voice'=>'#38a169','sms'=>'#d69e2e','combo'=>'#805ad5','drive'=>'#1a3c8f'];
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Packages - Admin Panel</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">
    <style>
        .price-col{font-size:15px;font-weight:800;color:var(--primary)}
        .cost-col{font-size:13px;color:#888}
        .type-badge{display:inline-block;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:700}
        .profit-preview{border-radius:8px;padding:10px 14px;font-size:13px;margin-top:8px;display:none}
        .sec-label{font-size:11px;font-weight:700;color:#aaa;text-transform:uppercase;letter-spacing:1px;margin:14px 0 8px;padding-bottom:6px;border-bottom:1px dashed #eee}
        .form-row-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px}
        .sync-bar{border-radius:10px;padding:12px 15px;margin-bottom:14px;font-size:13px;display:none;border-left:4px solid}
        @media(max-width:900px){.form-row-3{grid-template-columns:1fr 1fr}}
        @media(max-width:600px){.form-row-3{grid-template-columns:1fr}}
    </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>
            <h1><i class="fas fa-box"></i> Package Management</h1>
        </div>
        <div class="topbar-right">
            <select id="syncOpSelect" style="padding:9px 12px;border:2px solid #e8ecf4;border-radius:10px;font-size:13px;outline:none;margin-right:6px">
                <option value="">সব Operator</option>
                <option value="GP">Grameenphone</option>
                <option value="RB">Robi</option>
                <option value="AT">Airtel</option>
                <option value="BL">Banglalink</option>
                <option value="TT">Teletalk</option>
                <option value="BT">Brilliant</option>
            </select>
            <button id="syncBtn" onclick="syncDrives()" style="background:#f0fff4;color:#38a169;border:2px solid #c6f6d5;padding:9px 14px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer;margin-right:6px">
                <i class="fas fa-sync"></i> Drive Sync
            </button>
            <button onclick="bulkDelete()" style="background:#fff5f5;color:#e53e3e;border:2px solid #fed7d7;padding:9px 14px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer;margin-right:6px">
                <i class="fas fa-trash"></i> Selected Delete
            </button>
            <button class="btn-add" onclick="openAddModal()">
                <i class="fas fa-plus"></i> নতুন প্যাকেজ
            </button>
        </div>
    </div>

    <div class="content">
        <?php if ($flash): ?>
        <div class="flash flash-<?= $flash['type'] ?>"><?= $flash['msg'] ?></div>
        <?php endif; ?>

        <div class="sync-bar" id="syncBar"></div>

        <div class="filters">
            <form method="GET" style="display:flex;gap:10px;flex-wrap:wrap;width:100%;align-items:center">
                <select name="op" class="filter-input" onchange="this.form.submit()">
                    <option value="">সব অপারেটর</option>
                    <?php foreach ($operators as $o): ?>
                    <option value="<?= $o['id'] ?>" <?= $filterOp==$o['id']?'selected':'' ?>><?= $o['name'] ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="type" class="filter-input" onchange="this.form.submit()">
                    <option value="">সব টাইপ</option>
                    <?php foreach ($typeLabels as $k=>$v): ?>
                    <option value="<?= $k ?>" <?= $filterType===$k?'selected':'' ?>><?= $v ?></option>
                    <?php endforeach; ?>
                </select>
                <span style="font-size:13px;color:#666;margin-left:auto">মোট: <strong><?= count($packages) ?></strong> টি</span>
            </form>
        </div>

        <div class="table-wrap">
            <?php if (empty($packages)): ?>
            <div class="empty">
                <i class="fas fa-box-open"></i>
                কোনো প্যাকেজ নেই<br>
                <small>"নতুন প্যাকেজ" বা "Drive Sync" ক্লিক করুন</small>
            </div>
            <?php else: ?>
            <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox" id="selectAll" onclick="toggleAll(this)" style="width:15px;height:15px"></th>
                        <th>#</th><th>অপারেটর</th><th>নাম</th><th>টাইপ</th>
                        <th>মেয়াদ</th><th>বিক্রয়</th><th>ক্রয়</th><th>লাভ</th><th>স্ট্যাটাস</th><th>অ্যাকশন</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($packages as $p):
                    $profit    = $p['sell_price'] - $p['cost_price'];
                    $profitPct = $p['cost_price'] > 0 ? round(($profit/$p['cost_price'])*100,1) : 0;
                    $clr       = $typeColors[$p['type']] ?? '#666';
                ?>
                <tr>
                    <td style="color:#ccc;font-size:12px">
                        <input type="checkbox" class="pkg-cb" value="<?= $p['id'] ?>" style="width:15px;height:15px">
                    </td>
                    <td style="color:#ccc;font-size:12px"><?= $p['id'] ?></td>
                    <td><strong><?= htmlspecialchars($p['op_name']) ?></strong></td>
                    <td>
                        <strong style="font-size:13px"><?= htmlspecialchars($p['name']) ?></strong>
                        <?php if ($p['description']): ?>
                        <br><small style="color:#aaa;font-size:11px"><?= htmlspecialchars($p['description']) ?></small>
                        <?php endif; ?>
                    </td>
                    <td><span class="type-badge" style="background:<?= $clr ?>22;color:<?= $clr ?>"><?= $typeLabels[$p['type']] ?? $p['type'] ?></span></td>
                    <td style="font-size:12px;color:#666"><?= $p['validity'] ?: '-' ?></td>
                    <td class="price-col">৳<?= number_format($p['sell_price'],2) ?></td>
                    <td class="cost-col">৳<?= number_format($p['cost_price'],2) ?></td>
                    <td>
                        <span style="color:#38a169;font-size:12px;font-weight:700">+৳<?= number_format($profit,2) ?></span>
                        <br><span style="font-size:11px;color:#aaa"><?= $profitPct ?>%</span>
                    </td>
                    <td><span class="badge badge-<?= $p['status']==='active'?'active':'inactive' ?>"><?= $p['status']==='active'?'সক্রিয়':'বন্ধ' ?></span></td>
                    <td>
                        <div class="actions">
                            <button class="btn-sm btn-edit" onclick='openEditModal(<?= json_encode($p) ?>)'><i class="fas fa-edit"></i></button>
                            <form method="POST" style="display:inline">
                                <input type="hidden" name="action" value="toggle">
                                <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                <button type="submit" class="btn-sm <?= $p['status']==='active'?'btn-pr':'btn-ok' ?>">
                                    <i class="fas fa-<?= $p['status']==='active'?'pause':'play' ?>"></i>
                                </button>
                            </form>
                            <form method="POST" style="display:inline" onsubmit="return confirm('মুছবেন?')">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                <button type="submit" class="btn-sm btn-rj"><i class="fas fa-trash"></i></button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal" id="pkgModal">
    <div class="modal-box">
        <div class="modal-title" id="mTitle"><i class="fas fa-box" style="color:var(--primary)"></i> নতুন প্যাকেজ</div>
        <form method="POST" id="pkgForm">
            <input type="hidden" name="action" id="fAction" value="add">
            <input type="hidden" name="id"     id="fId"     value="">

            <div class="sec-label">📋 মূল তথ্য</div>
            <div class="form-row">
                <div class="form-group">
                    <label>অপারেটর *</label>
                    <select name="operator_id" id="fOp" 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="type" id="fType" required>
                        <option value="">বেছে নিন</option>
                        <?php foreach ($typeLabels as $k=>$v): ?>
                        <option value="<?= $k ?>"><?= $v ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label>প্যাকেজের নাম *</label>
                <input type="text" name="name" id="fName" placeholder="যেমন: 10GB Data 30 Days" required>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>পরিমাণ *</label>
                    <input type="number" name="amount" id="fAmt" placeholder="10" step="0.01" required>
                </div>
                <div class="form-group">
                    <label>মেয়াদ</label>
                    <input type="text" name="validity" id="fValidity" placeholder="30 Days">
                </div>
            </div>
            <div class="form-group">
                <label>বিবরণ</label>
                <input type="text" name="description" id="fDesc" placeholder="Social Pack, YouTube...">
            </div>

            <div class="sec-label">💰 মূল্য</div>
            <div class="form-row-3">
                <div class="form-group">
                    <label>ক্রয় মূল্য (৳) *</label>
                    <input type="number" name="cost_price" id="fCost" placeholder="0.00" step="0.01" oninput="calcProfit()" required>
                </div>
                <div class="form-group">
                    <label>বিক্রয় মূল্য (৳) *</label>
                    <input type="number" name="sell_price" id="fSell" placeholder="0.00" step="0.01" oninput="calcProfit()" required>
                </div>
                <div class="form-group">
                    <label>রিসেলার মূল্য (৳)</label>
                    <input type="number" name="reseller_price" id="fReseller" placeholder="0.00" step="0.01">
                </div>
            </div>
            <div class="profit-preview" id="profitPreview">
                💰 লাভ: <strong id="profitAmt">৳0</strong> (<span id="profitPct">0</span>%)
            </div>
            <div class="form-group" style="margin-top:12px">
                <label>স্ট্যাটাস</label>
                <select name="status" id="fStatus">
                    <option value="active">✅ সক্রিয়</option>
                    <option value="inactive">❌ বন্ধ</option>
                </select>
            </div>
            <div class="modal-btns">
                <button type="submit" class="btn-submit"><i class="fas fa-save"></i> সেভ করুন</button>
                <button type="button" class="btn-cancel-modal" onclick="closeModal()">বাতিল</button>
            </div>
        </form>
    </div>
</div>

<script>
function openAddModal() {
    document.getElementById('mTitle').innerHTML = '<i class="fas fa-plus-circle" style="color:var(--primary)"></i> নতুন প্যাকেজ';
    document.getElementById('fAction').value = 'add';
    document.getElementById('pkgForm').reset();
    document.getElementById('profitPreview').style.display = 'none';
    document.getElementById('pkgModal').classList.add('open');
}
function openEditModal(p) {
    document.getElementById('mTitle').innerHTML = '<i class="fas fa-edit" style="color:var(--primary)"></i> প্যাকেজ এডিট';
    document.getElementById('fAction').value   = 'edit';
    document.getElementById('fId').value       = p.id;
    document.getElementById('fOp').value       = p.operator_id;
    document.getElementById('fType').value     = p.type;
    document.getElementById('fName').value     = p.name;
    document.getElementById('fAmt').value      = p.amount;
    document.getElementById('fValidity').value = p.validity || '';
    document.getElementById('fDesc').value     = p.description || '';
    document.getElementById('fCost').value     = p.cost_price;
    document.getElementById('fSell').value     = p.sell_price;
    document.getElementById('fReseller').value = p.reseller_price || '';
    document.getElementById('fStatus').value   = p.status;
    calcProfit();
    document.getElementById('pkgModal').classList.add('open');
}
function closeModal() { document.getElementById('pkgModal').classList.remove('open'); }
function calcProfit() {
    const cost = parseFloat(document.getElementById('fCost').value) || 0;
    const sell = parseFloat(document.getElementById('fSell').value) || 0;
    const prev = document.getElementById('profitPreview');
    if (cost > 0 && sell > 0) {
        const profit = sell - cost;
        document.getElementById('profitAmt').textContent = '৳' + profit.toFixed(2);
        document.getElementById('profitPct').textContent = ((profit/cost)*100).toFixed(1);
        prev.style.display    = 'block';
        prev.style.background = profit >= 0 ? '#f0fff4' : '#fff5f5';
        prev.style.color      = profit >= 0 ? '#276749' : '#c53030';
        if (!document.getElementById('fReseller').value)
            document.getElementById('fReseller').value = (sell * 0.97).toFixed(2);
    } else { prev.style.display = 'none'; }
}
function syncDrives() {
    const op   = document.getElementById('syncOpSelect').value;
    const label = op || 'সব Operator';
    if (!confirm(label + ' এর Drive package sync করবেন?')) return;
    const btn  = document.getElementById('syncBtn');
    const bar  = document.getElementById('syncBar');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sync হচ্ছে...';
    bar.style.display = 'none';
    fetch('ajax/sync_st_drives.php' + (op ? '?operator=' + op : ''))
        .then(r => r.json())
        .then(d => {
            bar.style.display     = 'block';
            bar.style.background  = d.success ? '#f0fff4' : '#fff5f5';
            bar.style.color       = d.success ? '#276749' : '#c53030';
            bar.style.borderColor = d.success ? '#38a169' : '#e53e3e';
            bar.textContent = d.message;
            if (d.success && d.added > 0) setTimeout(() => location.reload(), 2000);
        })
        .catch(() => { bar.style.display='block'; bar.textContent='❌ Sync ব্যর্থ!'; })
        .finally(() => { btn.disabled=false; btn.innerHTML='<i class="fas fa-sync"></i> Drive Sync'; });
}

function toggleAll(cb) {
    document.querySelectorAll('.pkg-cb').forEach(c => c.checked = cb.checked);
}

function bulkDelete() {
    const ids = [...document.querySelectorAll('.pkg-cb:checked')].map(c => c.value);
    if (ids.length === 0) { alert('কোনো প্যাকেজ সিলেক্ট করা হয়নি!'); return; }
    if (!confirm(ids.length + ' টি প্যাকেজ মুছবেন?')) return;
    fetch('ajax/bulk_delete_pkg.php', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({ids})
    }).then(r=>r.json()).then(d=>{
        if (d.success) location.reload();
        else alert(d.message);
    });
}
document.getElementById('pkgModal').addEventListener('click', e => { if(e.target===document.getElementById('pkgModal')) closeModal(); });
</script>
</body>
</html>
