<?php
session_start();
require_once 'config.php';
require_once 'functions.php';
requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

$msg = ''; $error = '';

// Table des prix
try { $pdo->exec("CREATE TABLE IF NOT EXISTS pricing_plans (
    id INT AUTO_INCREMENT PRIMARY KEY,
    plan_key VARCHAR(50) UNIQUE NOT NULL,
    plan_name VARCHAR(100) NOT NULL,
    price_monthly DECIMAL(8,2) DEFAULT 0,
    price_yearly DECIMAL(8,2) DEFAULT 0,
    price_sale DECIMAL(8,2) DEFAULT NULL,
    sale_label VARCHAR(50) DEFAULT NULL,
    sale_active TINYINT(1) DEFAULT 0,
    features TEXT DEFAULT NULL,
    is_active TINYINT(1) DEFAULT 1,
    sort_order INT DEFAULT 0
)"); } catch(Exception $e){}

try { $pdo->exec("CREATE TABLE IF NOT EXISTS token_packages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    package_name VARCHAR(100) NOT NULL,
    token_amount INT NOT NULL,
    price DECIMAL(8,2) NOT NULL,
    price_sale DECIMAL(8,2) DEFAULT NULL,
    sale_label VARCHAR(50) DEFAULT NULL,
    sale_active TINYINT(1) DEFAULT 0,
    bonus_tokens INT DEFAULT 0,
    is_active TINYINT(1) DEFAULT 1,
    sort_order INT DEFAULT 0
)"); } catch(Exception $e){}

// Initialiser les forfaits si vides
if ((int)$pdo->query("SELECT COUNT(*) FROM pricing_plans")->fetchColumn() === 0) {
    $plans = [
        ['free','Gratuit',0,0,null,null,0,'Gages illimités|Chat|Classements',1,0],
        ['premium','Premium',9.99,89.99,7.99,'Soldes',0,'Tout Gratuit|Pastilles|Icônes Premium|Médias',1,1],
        ['premium_plus','Premium+',19.99,179.99,14.99,'Soldes',0,'Tout Premium|Thème perso|Icônes PP|Couleur chat',1,2],
    ];
    foreach ($plans as $p) {
        $pdo->prepare("INSERT INTO pricing_plans (plan_key,plan_name,price_monthly,price_yearly,price_sale,sale_label,sale_active,features,is_active,sort_order) VALUES (?,?,?,?,?,?,?,?,?,?)")->execute($p);
    }
}

if ((int)$pdo->query("SELECT COUNT(*) FROM token_packages")->fetchColumn() === 0) {
    $pkgs = [
        ['Débutant',500,4.99,null,null,0,0,1,0],
        ['Standard',1200,9.99,7.99,'Populaire',1,200,1,1],
        ['Pro',3000,19.99,null,null,0,500,1,2],
        ['Elite',7500,39.99,29.99,'Solde',0,1500,1,3],
    ];
    foreach ($pkgs as $p) {
        $pdo->prepare("INSERT INTO token_packages (package_name,token_amount,price,price_sale,sale_label,sale_active,bonus_tokens,is_active,sort_order) VALUES (?,?,?,?,?,?,?,?,?)")->execute($p);
    }
}

// Sauvegarder forfait
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_plan'])) {
    $id = (int)$_POST['plan_id'];
    $pdo->prepare("UPDATE pricing_plans SET price_monthly=?,price_yearly=?,price_sale=?,sale_label=?,sale_active=?,features=?,is_active=? WHERE id=?")
        ->execute([
            (float)$_POST['price_monthly'], (float)$_POST['price_yearly'],
            !empty($_POST['price_sale']) ? (float)$_POST['price_sale'] : null,
            htmlspecialchars($_POST['sale_label']??''), (int)($_POST['sale_active']??0),
            htmlspecialchars($_POST['features']??''), (int)($_POST['is_active']??1),
            $id
        ]);
    $msg = "Forfait mis à jour !";
}

// Sauvegarder package jetons
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_package'])) {
    $id = (int)$_POST['pkg_id'];
    if ($id === 0) {
        $pdo->prepare("INSERT INTO token_packages (package_name,token_amount,price,price_sale,sale_label,sale_active,bonus_tokens,is_active) VALUES (?,?,?,?,?,?,?,1)")
            ->execute([htmlspecialchars($_POST['pkg_name']), (int)$_POST['pkg_tokens'], (float)$_POST['pkg_price'],
                       !empty($_POST['pkg_sale']) ? (float)$_POST['pkg_sale'] : null,
                       htmlspecialchars($_POST['pkg_sale_label']??''), (int)($_POST['pkg_sale_active']??0), (int)($_POST['pkg_bonus']??0)]);
        $msg = "Package créé !";
    } else {
        $pdo->prepare("UPDATE token_packages SET package_name=?,token_amount=?,price=?,price_sale=?,sale_label=?,sale_active=?,bonus_tokens=?,is_active=? WHERE id=?")
            ->execute([htmlspecialchars($_POST['pkg_name']), (int)$_POST['pkg_tokens'], (float)$_POST['pkg_price'],
                       !empty($_POST['pkg_sale']) ? (float)$_POST['pkg_sale'] : null,
                       htmlspecialchars($_POST['pkg_sale_label']??''), (int)($_POST['pkg_sale_active']??0),
                       (int)($_POST['pkg_bonus']??0), (int)($_POST['pkg_active']??1), $id]);
        $msg = "Package mis à jour !";
    }
}

if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['delete_package'])) {
    $pdo->prepare("DELETE FROM token_packages WHERE id=?")->execute([(int)$_POST['pkg_id']]);
    $msg = "Package supprimé.";
}

// Charger
$plans    = $pdo->query("SELECT * FROM pricing_plans ORDER BY sort_order ASC")->fetchAll();
$packages = $pdo->query("SELECT * FROM token_packages ORDER BY sort_order ASC, price ASC")->fetchAll();
$editPkg  = null;
if (isset($_GET['edit_pkg'])) {
    $s = $pdo->prepare("SELECT * FROM token_packages WHERE id=?"); $s->execute([(int)$_GET['edit_pkg']]); $editPkg = $s->fetch();
}

include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<div class="container-fluid mt-3 mb-5" style="max-width:1000px;">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="admin.php" class="btn btn-outline-secondary btn-sm"><i class="fa fa-arrow-left fa-xs me-1"></i>Admin</a>
        <h4 class="oracle-text text-info mb-0" style="letter-spacing:2px;"><i class="fa fa-tag me-2"></i>PRIX & FORFAITS</h4>
    </div>

    <?php if ($msg): ?><div class="alert alert-success py-2 small"><?= htmlspecialchars($msg) ?></div><?php endif; ?>

    <!-- Forfaits -->
    <div class="card bg-dark border-info shadow mb-5">
        <div class="card-header py-2 fw-bold text-info small" style="background:#050520;letter-spacing:1px;">
            <i class="fa fa-star me-2"></i>FORFAITS / ABONNEMENTS
        </div>
        <div class="card-body">
            <div class="row g-3">
                <?php foreach ($plans as $p): ?>
                <div class="col-md-4">
                    <form method="POST">
                        <input type="hidden" name="plan_id" value="<?= $p['id'] ?>">
                        <div class="card bg-dark border-secondary h-100" style="border-color:<?= $p['plan_key']==='premium_plus'?'#a78bfa':($p['plan_key']==='premium'?'#ffc107':'#555') ?> !important;">
                            <div class="card-header py-1 fw-bold text-center small" style="font-size:0.72rem;color:<?= $p['plan_key']==='premium_plus'?'#a78bfa':($p['plan_key']==='premium'?'#ffc107':'#aaa') ?>;">
                                <?= htmlspecialchars($p['plan_name']) ?>
                            </div>
                            <div class="card-body p-2">
                                <div class="mb-2">
                                    <label class="small text-muted" style="font-size:0.6rem;">PRIX/MOIS ($)</label>
                                    <input type="number" name="price_monthly" step="0.01" value="<?= $p['price_monthly'] ?>" class="form-control form-control-sm bg-dark text-white border-secondary">
                                </div>
                                <div class="mb-2">
                                    <label class="small text-muted" style="font-size:0.6rem;">PRIX/AN ($)</label>
                                    <input type="number" name="price_yearly" step="0.01" value="<?= $p['price_yearly'] ?>" class="form-control form-control-sm bg-dark text-white border-secondary">
                                </div>
                                <div class="mb-2">
                                    <label class="small text-muted" style="font-size:0.6rem;">PRIX SOLDÉ ($)</label>
                                    <div class="d-flex gap-1">
                                        <input type="number" name="price_sale" step="0.01" value="<?= $p['price_sale'] ?>" placeholder="0.00" class="form-control form-control-sm bg-dark text-white border-secondary">
                                        <div class="form-check d-flex align-items-center ms-1">
                                            <input class="form-check-input" type="checkbox" name="sale_active" value="1" <?= $p['sale_active']?'checked':'' ?> id="sa<?= $p['id'] ?>">
                                            <label class="form-check-label ms-1" style="font-size:0.6rem;" for="sa<?= $p['id'] ?>">Actif</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="mb-2">
                                    <label class="small text-muted" style="font-size:0.6rem;">ÉTIQUETTE SOLDE</label>
                                    <input type="text" name="sale_label" value="<?= htmlspecialchars($p['sale_label']??'') ?>" placeholder="ex: -20%" class="form-control form-control-sm bg-dark text-white border-secondary">
                                </div>
                                <div class="mb-2">
                                    <label class="small text-muted" style="font-size:0.6rem;">FONCTIONNALITÉS (séparées par |)</label>
                                    <textarea name="features" rows="2" class="form-control form-control-sm bg-dark text-white border-secondary" style="font-size:0.65rem;"><?= htmlspecialchars($p['features']??'') ?></textarea>
                                </div>
                                <button type="submit" name="save_plan" class="btn btn-sm btn-outline-info w-100" style="font-size:0.65rem;">
                                    <i class="fa fa-floppy-disk me-1"></i>Sauvegarder
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Packages jetons -->
    <div class="card bg-dark border-warning shadow">
        <div class="card-header py-2 fw-bold small" style="background:#1a1200;color:#ffc107;letter-spacing:1px;">
            <i class="fa fa-coins me-2"></i>PACKAGES DE JETONS
        </div>
        <div class="card-body">
            <!-- Liste -->
            <div class="table-responsive mb-4">
                <table class="table table-dark table-sm table-hover" style="font-size:0.72rem;">
                    <thead><tr>
                        <th>Nom</th><th>Jetons</th><th>Bonus</th><th>Prix $</th><th>Prix soldé</th><th>Étiquette</th><th>Solde actif</th><th>Actif</th><th></th>
                    </tr></thead>
                    <tbody>
                        <?php foreach ($packages as $pk): ?>
                        <tr>
                            <td class="fw-bold"><?= htmlspecialchars($pk['package_name']) ?></td>
                            <td class="text-warning">◆ <?= number_format($pk['token_amount']) ?></td>
                            <td class="text-success"><?= $pk['bonus_tokens']>0?'+'.number_format($pk['bonus_tokens']):'-' ?></td>
                            <td><?= number_format($pk['price'],2) ?>$</td>
                            <td><?= $pk['price_sale'] ? number_format($pk['price_sale'],2).'$' : '—' ?></td>
                            <td><?= htmlspecialchars($pk['sale_label']??'—') ?></td>
                            <td><?= $pk['sale_active'] ? '<span class="badge bg-success">Oui</span>' : '<span class="badge bg-secondary">Non</span>' ?></td>
                            <td><?= $pk['is_active']  ? '<span class="badge bg-success">Oui</span>' : '<span class="badge bg-danger">Non</span>'  ?></td>
                            <td>
                                <a href="?edit_pkg=<?= $pk['id'] ?>" class="btn btn-xs btn-outline-info py-0" style="font-size:0.6rem;">✏</a>
                                <form method="POST" class="d-inline" onsubmit="return confirm('Supprimer ?')">
                                    <input type="hidden" name="pkg_id" value="<?= $pk['id'] ?>">
                                    <button type="submit" name="delete_package" class="btn btn-xs btn-outline-danger py-0" style="font-size:0.6rem;">✕</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Formulaire ajouter/modifier -->
            <div class="card bg-dark border-secondary">
                <div class="card-header py-2 text-muted small" style="font-size:0.65rem;background:#0a0a0a;letter-spacing:1px;">
                    <?= $editPkg ? 'MODIFIER — '.htmlspecialchars($editPkg['package_name']) : 'AJOUTER UN PACKAGE' ?>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="pkg_id" value="<?= $editPkg['id'] ?? 0 ?>">
                        <div class="row g-2">
                            <div class="col-md-3"><label class="small text-muted" style="font-size:0.6rem;">NOM</label>
                                <input type="text" name="pkg_name" value="<?= htmlspecialchars($editPkg['package_name']??'') ?>" required class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                            <div class="col-md-2"><label class="small text-muted" style="font-size:0.6rem;">JETONS</label>
                                <input type="number" name="pkg_tokens" value="<?= $editPkg['token_amount']??500 ?>" required class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                            <div class="col-md-2"><label class="small text-muted" style="font-size:0.6rem;">BONUS JETONS</label>
                                <input type="number" name="pkg_bonus" value="<?= $editPkg['bonus_tokens']??0 ?>" class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                            <div class="col-md-2"><label class="small text-muted" style="font-size:0.6rem;">PRIX ($)</label>
                                <input type="number" name="pkg_price" step="0.01" value="<?= $editPkg['price']??9.99 ?>" required class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                            <div class="col-md-2"><label class="small text-muted" style="font-size:0.6rem;">PRIX SOLDÉ ($)</label>
                                <input type="number" name="pkg_sale" step="0.01" value="<?= $editPkg['price_sale']??'' ?>" placeholder="Optionnel" class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                            <div class="col-md-2"><label class="small text-muted" style="font-size:0.6rem;">ÉTIQUETTE</label>
                                <input type="text" name="pkg_sale_label" value="<?= htmlspecialchars($editPkg['sale_label']??'') ?>" placeholder="-20%" class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                            <div class="col-md-2 d-flex align-items-end gap-2">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="pkg_sale_active" value="1" <?= ($editPkg['sale_active']??0)?'checked':'' ?> id="psa">
                                    <label class="form-check-label small text-muted" for="psa" style="font-size:0.6rem;">Solde actif</label>
                                </div>
                            </div>
                            <div class="col-12 mt-2">
                                <button type="submit" name="save_package" class="btn btn-warning btn-sm fw-bold text-dark">
                                    <i class="fa fa-floppy-disk me-1"></i><?= $editPkg ? 'Mettre à jour' : 'Ajouter' ?>
                                </button>
                                <?php if ($editPkg): ?>
                                <a href="admin_pricing.php" class="btn btn-outline-secondary btn-sm ms-2">Annuler</a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
