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

// Auto-create table
try {
    $db->exec("CREATE TABLE IF NOT EXISTS user_packages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        description TEXT,
        topup_commission DECIMAL(5,2) DEFAULT 0.00,
        intl_commission DECIMAL(5,2) DEFAULT 0.00,
        pin_commission DECIMAL(5,2) DEFAULT 0.00,
        gift_commission DECIMAL(5,2) DEFAULT 0.00,
        card_commission DECIMAL(5,2) DEFAULT 0.00,
        drive_commission DECIMAL(5,2) DEFAULT 0.00,
        manual_drive_commission DECIMAL(5,2) DEFAULT 0.00,
        is_active TINYINT(1) DEFAULT 1,
        upgrade_fee DECIMAL(10,2) DEFAULT 0.00,
        is_default TINYINT(1) DEFAULT 0,
        color VARCHAR(20) DEFAULT '#1a3c8f',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    $cnt = $db->query("SELECT COUNT(*) FROM user_packages")->fetchColumn();
    if ($cnt == 0) {
        $db->exec("INSERT INTO user_packages (name,description,topup_commission,intl_commission,pin_commission,gift_commission,card_commission,drive_commission,upgrade_fee,is_active,is_default,color) VALUES
            ('Basic','Default package for all users',0,0,0,0,0,0,0,1,1,'#1a3c8f'),
            ('Silver','Silver member benefits',2.00,1.50,1.50,1.50,1.50,1.00,100,1,0,'#718096'),
            ('Gold','Gold member benefits',3.00,2.50,2.50,2.50,2.50,2.00,300,1,0,'#d69e2e'),
            ('Platinum','Premium package',5.00,4.00,4.00,4.00,4.00,3.00,500,1,0,'#805ad5')");
    }
    try { $db->exec("ALTER TABLE users ADD COLUMN package_id INT DEFAULT 1"); } catch(Exception $e2) {}
    try { $db->exec("ALTER TABLE user_packages ADD COLUMN manual_drive_commission DECIMAL(5,2) DEFAULT 0.00"); } catch(Exception $ex) {}
    try { $db->exec("ALTER TABLE user_packages ADD COLUMN upgrade_fee DECIMAL(10,2) DEFAULT 0.00"); } catch(Exception $e3) {}
    // Set default upgrade fees
    $db->exec("UPDATE user_packages SET upgrade_fee=0   WHERE name='Basic'    AND upgrade_fee=0");
    $db->exec("UPDATE user_packages SET upgrade_fee=100 WHERE name='Silver'   AND upgrade_fee=0");
    $db->exec("UPDATE user_packages SET upgrade_fee=300 WHERE name='Gold'     AND upgrade_fee=0");
    $db->exec("UPDATE user_packages SET upgrade_fee=500 WHERE name='Platinum' AND upgrade_fee=0");
} catch(Exception $e) {}

$msg = null;
if (isset($_GET['ok'])) $msg = ['ok'=>true,'text'=>'✅ Saved successfully!'];

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

    if ($action === 'add' || $action === 'edit') {
        $name  = trim($_POST['name'] ?? '');
        $desc  = trim($_POST['description'] ?? '');
        $color = trim($_POST['color'] ?? '#1a3c8f');
        $tc    = floatval($_POST['topup_commission'] ?? 0);
        $ic    = floatval($_POST['intl_commission']  ?? 0);
        $pc    = floatval($_POST['pin_commission']   ?? 0);
        $gc    = floatval($_POST['gift_commission']  ?? 0);
        $cc    = floatval($_POST['card_commission']  ?? 0);
        $dc    = floatval($_POST['drive_commission'] ?? 0);
        $mdc   = floatval($_POST['manual_drive_commission'] ?? 0);
        $uf    = floatval($_POST['upgrade_fee']      ?? 0);
        $act   = intval($_POST['is_active'] ?? 1);

        if (!$name) { $msg = ['ok'=>false,'text'=>'Package name required!']; }
        else {
            if ($action === 'add') {
                $db->prepare("INSERT INTO user_packages (name,description,topup_commission,intl_commission,pin_commission,gift_commission,card_commission,drive_commission,manual_drive_commission,upgrade_fee,is_active,color) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)")
                   ->execute([$name,$desc,$tc,$ic,$pc,$gc,$cc,$dc,$mdc,$uf,$act,$color]);
                $msg = ['ok'=>true,'text'=>"Package '$name' created!"];
                header('Location: user_packages.php?ok=1'); exit;
            } else {
                $id = intval($_POST['id']);
                $db->prepare("UPDATE user_packages SET name=?,description=?,topup_commission=?,intl_commission=?,pin_commission=?,gift_commission=?,card_commission=?,drive_commission=?,manual_drive_commission=?,upgrade_fee=?,is_active=?,color=? WHERE id=?")
                   ->execute([$name,$desc,$tc,$ic,$pc,$gc,$cc,$dc,$mdc,$uf,$act,$color,$id]);
                $msg = ['ok'=>true,'text'=>"Package updated!"];
                header('Location: user_packages.php?ok=1'); exit;
            }
        }
    }

    if ($action === 'delete') {
        $id = intval($_POST['id']);
        // Move users to basic package first
        $db->prepare("UPDATE users SET package_id=1 WHERE package_id=?")->execute([$id]);
        $db->prepare("DELETE FROM user_packages WHERE id!=1 AND id=?")->execute([$id]);
        $msg = ['ok'=>true,'text'=>'Package deleted!'];
        header('Location: user_packages.php?ok=1'); exit;
    }

    if ($action === 'assign') {
        $userId = intval($_POST['user_id']);
        $pkgId  = intval($_POST['package_id']);
        $db->prepare("UPDATE users SET package_id=? WHERE id=?")->execute([$pkgId,$userId]);
        header('Content-Type: application/json');
        echo json_encode(['success'=>true]); exit;
    }

    if ($action === 'set_default') {
        $id = intval($_POST['id']);
        $db->exec("UPDATE user_packages SET is_default=0");
        $db->prepare("UPDATE user_packages SET is_default=1 WHERE id=?")->execute([$id]);
        $msg = ['ok'=>true,'text'=>'Default package set!'];
        header('Location: user_packages.php?ok=1'); exit;
    }
}

$packages = $db->query("SELECT p.*, COUNT(u.id) as user_count FROM user_packages p LEFT JOIN users u ON u.package_id=p.id GROUP BY p.id ORDER BY p.id")->fetchAll();
$users    = $db->query("SELECT u.id, u.name, u.phone, u.role, COALESCE(p.name,'Basic') as pkg_name, COALESCE(p.color,'#1a3c8f') as pkg_color, COALESCE(u.package_id,1) as package_id FROM users u LEFT JOIN user_packages p ON u.package_id=p.id ORDER BY u.name LIMIT 100")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>User Packages - 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">
<style>
.pkg-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px;margin-bottom:20px}
.pkg-card{background:white;border-radius:14px;box-shadow:0 2px 10px rgba(0,0,0,0.07);overflow:hidden;border-top:4px solid var(--c)}
.pkg-head{padding:16px 18px 12px;display:flex;align-items:center;justify-content:space-between}
.pkg-name{font-size:16px;font-weight:800;color:var(--dark)}
.pkg-badge{padding:3px 10px;border-radius:20px;font-size:11px;font-weight:700;color:white}
.pkg-body{padding:0 18px 16px}
.pkg-desc{font-size:12px;color:#888;margin-bottom:12px}
.comm-row{display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #f5f5f5;font-size:13px}
.comm-row:last-child{border:none}
.comm-lbl{color:#666;display:flex;align-items:center;gap:6px}
.comm-val{font-weight:700;color:var(--primary)}
.comm-val.zero{color:#ddd}
.pkg-foot{padding:12px 18px;background:#f8fafc;display:flex;gap:8px;align-items:center}
.pkg-users{font-size:12px;color:#888;flex:1}
.btn{padding:8px 14px;border:none;border-radius:9px;font-size:12px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:5px}
.btn-primary{background:var(--primary);color:white}
.btn-edit{background:#ebf8ff;color:#2b6cb0}
.btn-del{background:#fff5f5;color:#e53e3e}
.btn-def{background:#f0fff4;color:#276749}
.card{background:white;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,0.05);margin-bottom:18px;overflow:hidden}
.card-h{padding:14px 18px;border-bottom:1px solid #f5f5f5;font-size:14px;font-weight:700;color:var(--dark);display:flex;align-items:center;gap:8px}
.card-b{padding:18px}
.alert{padding:11px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}
.frow{display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:10px;margin-bottom:12px}
.fg{display:flex;flex-direction:column;gap:4px}
.fg label{font-size:12px;font-weight:600;color:#555}
.fg input,.fg select,.fg textarea{padding:9px 11px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none;width:100%}
.fg input:focus,.fg select:focus{border-color:var(--primary)}
.comm-input-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:10px 0}
table{width:100%;border-collapse:collapse}
th{padding:9px 12px;text-align:left;font-size:11px;color:#888;font-weight:700;text-transform:uppercase;border-bottom:2px solid #f5f5f5}
td{padding:10px 12px;border-bottom:1px solid #f9f9f9;font-size:13px;vertical-align:middle}
tr:last-child td{border:none}
tr:hover td{background:#fafbff}
.pkg-sel{padding:6px 10px;border:2px solid #e8ecf4;border-radius:8px;font-size:12px;font-weight:600;outline:none;cursor:pointer}
.modal-ov{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9999;align-items:center;justify-content:center}
.modal-ov.show{display:flex}
.modal-box{background:white;border-radius:14px;padding:22px;width:94%;max-width:520px;max-height:90vh;overflow-y:auto}
.modal-box h3{font-size:16px;font-weight:800;margin-bottom:16px;color:var(--dark)}
.gap-btn{display:flex;gap:8px;margin-top:14px}
</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">User Package Management</span>
    </div>
    <div class="topbar-right">
        <button class="btn btn-primary" onclick="openAdd()"><i class="fas fa-plus"></i> New Package</button>
    </div>
</div>

<div class="content">
<?php if($msg): ?>
<div class="alert <?= $msg['ok']?'alert-ok':'alert-err' ?>"><?= $msg['ok']?'✅':'❌' ?> <?= htmlspecialchars($msg['text']) ?></div>
<?php endif; ?>

<!-- Package Cards -->
<div class="pkg-grid">
<?php foreach($packages as $p): ?>
<div class="pkg-card" style="--c:<?= $p['color'] ?>">
    <div class="pkg-head">
        <div>
            <div class="pkg-name"><?= htmlspecialchars($p['name']) ?></div>
            <?php if($p['description']): ?><div style="font-size:11px;color:#888;margin-top:2px"><?= htmlspecialchars($p['description']) ?></div><?php endif; ?>
        </div>
        <span class="pkg-badge" style="background:<?= $p['color'] ?>"><?= $p['is_default']?'Default':($p['is_active']?'Active':'Inactive') ?></span>
    </div>
    <div class="pkg-body">
        <div class="comm-row"><span class="comm-lbl">📱 Topup</span><span class="comm-val <?= $p['topup_commission']>0?'':'zero' ?>"><?= $p['topup_commission'] ?>%</span></div>
        <div class="comm-row"><span class="comm-lbl">🌍 Intl Recharge</span><span class="comm-val <?= $p['intl_commission']>0?'':'zero' ?>"><?= $p['intl_commission'] ?>%</span></div>
        <div class="comm-row"><span class="comm-lbl">🔑 PIN</span><span class="comm-val <?= $p['pin_commission']>0?'':'zero' ?>"><?= $p['pin_commission'] ?>%</span></div>
        <div class="comm-row"><span class="comm-lbl">🎁 Gift Card</span><span class="comm-val <?= $p['gift_commission']>0?'':'zero' ?>"><?= $p['gift_commission'] ?>%</span></div>
        <div class="comm-row"><span class="comm-lbl">📞 Calling Card</span><span class="comm-val <?= $p['card_commission']>0?'':'zero' ?>"><?= $p['card_commission'] ?>%</span></div>
        <div class="comm-row"><span class="comm-lbl">⚡ Drive</span><span class="comm-val <?= $p['drive_commission']>0?'':'zero' ?>"><?= $p['drive_commission'] ?>%</span></div>
        <div class="comm-row"><span class="comm-lbl">📦 Manual Drive</span><span class="comm-val <?= ($p['manual_drive_commission']??0)>0?'':'zero' ?>"><?= $p['manual_drive_commission']??0 ?>%</span></div>
        <div class="comm-row" style="border-top:2px solid #f0f0f0;margin-top:6px;padding-top:8px">
            <span class="comm-lbl" style="font-weight:700">💳 Upgrade Fee</span>
            <span style="font-weight:700;color:<?= floatval($p['upgrade_fee']??0)>0?'#e53e3e':'#38a169' ?>">
                <?= floatval($p['upgrade_fee']??0)>0 ? CURRENCY.number_format($p['upgrade_fee'],0) : 'Free' ?>
            </span>
        </div>
    </div><!-- pkg-body -->
    <div class="pkg-foot">
        <span class="pkg-users"><i class="fas fa-users"></i> <?= $p['user_count'] ?> users</span>
        <?php if(!$p['is_default']): ?>
        <form method="POST" style="display:inline">
            <input type="hidden" name="action" value="set_default">
            <input type="hidden" name="id" value="<?= $p['id'] ?>">
            <button type="submit" class="btn btn-def" style="font-size:11px;padding:5px 10px">Set Default</button>
        </form>
        <?php endif; ?>
        <button class="btn btn-edit" onclick="openEdit(<?= htmlspecialchars(json_encode($p),ENT_QUOTES) ?>)"><i class="fas fa-edit"></i></button>
        <?php if(!$p['is_default']): ?>
        <form method="POST" onsubmit="return confirm('Delete this package?')" style="display:inline">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="<?= $p['id'] ?>">
            <button type="submit" class="btn btn-del"><i class="fas fa-trash"></i></button>
        </form>
        <?php endif; ?>
    </div>
</div>
<?php endforeach; ?>
</div>

<!-- User Package Assignment -->
<div class="card">
    <div class="card-h"><i class="fas fa-users" style="color:var(--primary)"></i> Assign Package to Users</div>
    <div style="overflow-x:auto">
    <table>
        <thead><tr>
            <th>User</th><th>Phone</th><th>Role</th><th>Current Package</th><th>Change Package</th>
        </tr></thead>
        <tbody>
        <?php foreach($users as $u): ?>
        <tr>
            <td><strong><?= htmlspecialchars($u['name']) ?></strong></td>
            <td style="font-family:monospace;font-size:12px"><?= $u['phone'] ?></td>
            <td><span style="background:#f0f4ff;color:var(--primary);padding:3px 9px;border-radius:20px;font-size:11px;font-weight:700"><?= ucfirst($u['role']) ?></span></td>
            <td><span style="background:<?= $u['pkg_color'] ?>;color:white;padding:4px 11px;border-radius:20px;font-size:11px;font-weight:700"><?= htmlspecialchars($u['pkg_name']) ?></span></td>
            <td>
                <select class="pkg-sel" onchange="assignPackage(<?= $u['id'] ?>,this.value,this)">
                    <?php foreach($packages as $p): ?>
                    <option value="<?= $p['id'] ?>" <?= $p['id']==$u['package_id']?'selected':'' ?>
                        style="font-weight:600"><?= htmlspecialchars($p['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
</div>

</div><!-- content -->
</div><!-- main -->

<!-- Add/Edit Modal -->
<div class="modal-ov" id="pkgModal" onclick="if(event.target===this)closeModal()">
<div class="modal-box">
    <h3 id="modalTitle"><i class="fas fa-box"></i> New Package</h3>
    <form method="POST" id="pkgForm">
        <input type="hidden" name="action" id="formAction" value="add">
        <input type="hidden" name="id" id="formId">

        <div style="display:grid;grid-template-columns:1fr auto;gap:10px;margin-bottom:10px">
            <div class="fg"><label>Package Name *</label><input name="name" id="fName" placeholder="Gold, Premium..." required></div>
            <div class="fg"><label>Color</label><input type="color" name="color" id="fColor" value="#1a3c8f" style="height:42px;padding:3px;cursor:pointer"></div>
        </div>
        <div class="fg" style="margin-bottom:12px">
            <label>Description (optional)</label>
            <input name="description" id="fDesc" placeholder="Brief description...">
        </div>

        <div style="background:#f8fafc;border-radius:10px;padding:14px;margin-bottom:12px">
            <div style="font-size:12px;font-weight:700;color:#555;margin-bottom:4px;text-transform:uppercase;letter-spacing:0.5px">
                💰 Commission Rates
            </div>
            <div style="font-size:11px;color:#aaa;margin-bottom:10px;line-height:1.6">
                📱 Topup/Intl: recharge amount এর % &nbsp;|&nbsp;
                ⚡ Drive: API cashback এর % (100% = পুরো cashback) &nbsp;|&nbsp;
                🎴 Card: card এর own commission এর %
            </div>
            <div class="comm-input-grid">
                <div class="fg">
                    <label>📱 Topup %</label>
                    <input type="number" name="topup_commission" id="fTc" step="0.01" min="0" max="100" placeholder="0.00" value="0">
                </div>
                <div class="fg">
                    <label>🌍 Intl Recharge %</label>
                    <input type="number" name="intl_commission" id="fIc" step="0.01" min="0" max="100" placeholder="0.00" value="0">
                </div>
                <div class="fg">
                    <label>🔑 PIN %</label>
                    <input type="number" name="pin_commission" id="fPc" step="0.01" min="0" max="100" placeholder="0.00" value="0">
                </div>
                <div class="fg">
                    <label>🎁 Gift Card %</label>
                    <input type="number" name="gift_commission" id="fGc" step="0.01" min="0" max="100" placeholder="0.00" value="0">
                </div>
                <div class="fg">
                    <label>🎴 Card % <span style="font-size:10px;color:#aaa">(of card commission)</span></label>
                    <input type="number" name="card_commission" id="fCc" step="0.01" min="0" max="100" placeholder="0.00" value="0">
                </div>
                <div class="fg">
                    <label>⚡ Drive % <span style="font-size:10px;color:#aaa">(of API cashback)</span></label>
                    <input type="number" name="drive_commission" id="fDc" step="0.01" min="0" max="100" placeholder="0.00" value="0">
                </div>
                <div class="fg">
                    <label>📦 Manual Drive %</label>
                    <input type="number" name="manual_drive_commission" id="fMdc" step="0.01" min="0" max="100" placeholder="0.00" value="0">
                </div>
            </div>
        </div>

        <div class="fg" style="margin-bottom:4px">
            <label>Status</label>
            <select name="is_active" id="fActive">
                <option value="1">Active</option>
                <option value="0">Inactive</option>
            </select>
        </div>

        <div class="fg" style="margin-bottom:4px">
            <label>💳 Upgrade Fee (৳) — user এর account থেকে কাটবে</label>
            <input type="number" name="upgrade_fee" id="fUf" step="0.01" min="0" placeholder="0 = Free" value="0">
        </div>
        <div class="gap-btn">
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Package</button>
            <button type="button" class="btn" style="background:#f5f5f5" onclick="closeModal()">Cancel</button>
        </div>
    </form>
</div>
</div>

<script>
function openAdd() {
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-plus-circle"></i> New Package';
    document.getElementById('formAction').value = 'add';
    document.getElementById('formId').value = '';
    document.getElementById('fName').value = '';
    document.getElementById('fDesc').value = '';
    document.getElementById('fColor').value = '#1a3c8f';
    ['fTc','fIc','fPc','fGc','fCc','fDc','fUf'].forEach(id => document.getElementById(id).value = '0');
    document.getElementById('fActive').value = '1';
    document.getElementById('pkgModal').classList.add('show');
}

function openEdit(p) {
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-edit"></i> Edit Package';
    document.getElementById('formAction').value = 'edit';
    document.getElementById('formId').value = p.id;
    document.getElementById('fName').value = p.name;
    document.getElementById('fDesc').value = p.description || '';
    document.getElementById('fColor').value = p.color || '#1a3c8f';
    document.getElementById('fTc').value = p.topup_commission;
    document.getElementById('fIc').value = p.intl_commission;
    document.getElementById('fPc').value = p.pin_commission;
    document.getElementById('fGc').value = p.gift_commission;
    document.getElementById('fCc').value = p.card_commission;
    document.getElementById('fDc').value = p.drive_commission;
    document.getElementById('fMdc').value = p.manual_drive_commission||0;
    document.getElementById('fUf').value = p.upgrade_fee || 0;
    document.getElementById('fActive').value = p.is_active;
    document.getElementById('pkgModal').classList.add('show');
}

function closeModal() { document.getElementById('pkgModal').classList.remove('show'); }

function assignPackage(userId, pkgId, sel) {
    fetch('user_packages.php', {
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'action=assign&user_id='+userId+'&package_id='+pkgId
    }).then(r=>r.json()).then(d=>{
        if(d.success){
            sel.style.borderColor='#38a169';
            setTimeout(()=>sel.style.borderColor='',2000);
        }
    });
}
</script>
</body>
</html>
