<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

requireLogin();
$user = getConnectedUser($pdo);
if (!$user) { header("Location: index.php"); exit; }
$userId      = (int)$user['id'];
$currentTier = $user['tier'] ?? 'free';

$msg = ''; $step = 'plans'; // plans | billing | confirm

$plans = [
    'free' => [
        'label' => 'FREE', 'price' => '0$', 'price_num' => 0, 'color' => 'secondary',
        'features' => ['✅ Dashboard','✅ Créer des gages','✅ Voter','✅ Chat du cercle','❌ Photos limitées','❌ Pas de couleur chat'],
    ],
    'premium' => [
        'label' => 'PREMIUM', 'price' => '4.99$', 'price_num' => 4.99, 'period' => '/ mois', 'color' => 'warning',
        'features' => ['✅ Tout du Free','✅ 5 photos par gage','✅ Couleur dans le chat','✅ Icônes premium','✅ 5 cercles','❌ Pas de photo dans le chat'],
    ],
    'premium_plus' => [
        'label' => 'PREMIUM+', 'price' => '9.99$', 'price_num' => 9.99, 'period' => '/ mois', 'color' => 'info',
        'features' => ['✅ Tout du Premium','✅ Photos dans le chat','✅ Couleur texte chat','✅ 20 cercles','✅ Badge exclusif','✅ Support prioritaire'],
    ],
];

// ÉTAPE 2 : Afficher la page de facturation
if (isset($_GET['plan'])) {
    $step     = 'billing';
    $planKey  = $_GET['plan'];
    $planInfo = $plans[$planKey] ?? null;
    if (!$planInfo || $planKey === 'free') { header("Location: upgrade.php"); exit; }
}

// ÉTAPE 3 : Confirmer l'achat (simulé)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_purchase'])) {
    $newTier = $_POST['buy_tier'] ?? '';
    if (in_array($newTier, ['premium','premium_plus'])) {
        $renewalDate = date('Y-m-d', strtotime('+1 month'));
        $pdo->prepare("UPDATE users SET tier=?, renewal_date=? WHERE id=?")->execute([$newTier, $renewalDate, $userId]);
        $currentTier = $newTier;
        addNotification($pdo, $userId, "Bienvenue en mode " . strtoupper($newTier) . " !", "index.php");
        $msg  = "Achat confirme ! Tu es maintenant " . strtoupper($newTier) . " jusqu'au {$renewalDate}.";
        $step = 'plans';
    }
}

$taxGST = 0.05; $taxQST = 0.09975;

include 'header.php';
?>

<?php if ($msg): ?>
<div class="container mt-3"><div class="alert alert-success"><?= $msg ?></div></div>
<?php endif; ?>

<?php if ($step === 'billing' && isset($planInfo)): ?>
<!-- PAGE FACTURATION -->
<div class="container mt-4" style="max-width:500px;">
    <a href="index.php" class="btn btn-outline-secondary btn-sm mb-3">&larr; Dashboard</a>
    <h5 class="text-warning fw-bold mb-4">Résumé de commande</h5>

    <div class="card bg-dark border-<?= $planInfo['color'] ?> shadow mb-3">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="text-<?= $planInfo['color'] ?> fw-bold mb-0"><?= $planInfo['label'] ?></h5>
                <span class="text-white fw-bold" style="font-size:1.2rem;"><?= $planInfo['price'] ?><small class="text-muted" style="font-size:0.7rem;"> <?= $planInfo['period']??'' ?></small></span>
            </div>
            <hr class="border-secondary">
            <?php
            $price    = $planInfo['price_num'];
            $gst      = round($price * $taxGST, 2);
            $qst      = round($price * $taxQST, 2);
            $total    = round($price + $gst + $qst, 2);
            ?>
            <table class="table table-dark table-sm small mb-0">
                <tr><td class="text-muted">Sous-total</td><td class="text-end text-white"><?= number_format($price,2) ?>$</td></tr>
                <tr><td class="text-muted">TPS (5%)</td><td class="text-end text-white"><?= number_format($gst,2) ?>$</td></tr>
                <tr><td class="text-muted">TVQ (9.975%)</td><td class="text-end text-white"><?= number_format($qst,2) ?>$</td></tr>
                <tr class="border-top border-secondary">
                    <td class="text-white fw-bold">TOTAL</td>
                    <td class="text-end text-warning fw-bold" style="font-size:1.1rem;"><?= number_format($total,2) ?>$</td>
                </tr>
            </table>
        </div>
    </div>

    <div class="card bg-dark border-secondary shadow mb-3 p-3">
        <div class="text-muted small mb-2">Paiement via PayPal — bientôt disponible</div>
        <form method="POST">
            <input type="hidden" name="buy_tier" value="<?= htmlspecialchars($planKey) ?>">
            <button type="submit" name="confirm_purchase"
                    class="btn btn-<?= $planInfo['color'] ?> fw-bold w-100 mb-2">
                CONFIRMER L'ACHAT — <?= number_format($total,2) ?>$
            </button>
        </form>
        <a href="upgrade.php" class="btn btn-outline-secondary w-100 btn-sm">Annuler</a>
        <small class="text-muted d-block mt-2" style="font-size:0.65rem;">
            En confirmant, tu acceptes nos conditions. Achat simule — aucun montant reel preleve pour l'instant.
        </small>
    </div>
</div>

<?php else: ?>
<!-- PAGE PLANS -->
<div class="container mt-4">
    <h5 class="oracle-text text-primary mb-2">Choisir un forfait</h5>
    <p class="text-muted small mb-4">Choisis le niveau qui te correspond.</p>

    <div class="row g-4 justify-content-center">
    <?php foreach ($plans as $key => $plan):
        $isCurrent = ($currentTier === $key);
        $isPopular = ($key === 'premium');
    ?>
    <div class="col-md-4">
        <div class="card bg-dark h-100 shadow <?= $isCurrent ? "border-{$plan['color']}" : 'border-secondary' ?>"
             style="<?= $isCurrent ? "border-width:2px;" : "" ?>">
            <?php if ($isPopular): ?>
                <div class="text-center py-1 bg-warning text-dark fw-bold" style="font-size:0.7rem;border-radius:4px 4px 0 0;">LE PLUS POPULAIRE</div>
            <?php endif; ?>
            <?php if ($isCurrent): ?>
                <div class="text-center py-1 bg-<?= $plan['color'] ?> text-dark fw-bold" style="font-size:0.7rem;border-radius:4px 4px 0 0;">VOTRE FORFAIT ACTUEL</div>
            <?php endif; ?>
            <div class="card-body text-center">
                <h5 class="text-<?= $plan['color'] ?> fw-bold"><?= $plan['label'] ?></h5>
                <div class="text-white fw-bold mb-3" style="font-size:1.5rem;"><?= $plan['price'] ?>
                    <?php if (!empty($plan['period'])): ?><small class="text-white" style="font-size:0.7rem;"><?= $plan['period'] ?></small><?php endif; ?>
                </div>
                <ul class="list-unstyled text-start mb-3 small">
                    <?php foreach ($plan['features'] as $f): ?>
                    <li class="mb-1 <?= strpos($f,'❌') === 0 ? 'text-secondary' : 'text-white' ?>"><?= $f ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <div class="card-footer border-secondary bg-transparent pb-3 px-3">
                <?php
                $tierOrder = ['free'=>0,'premium'=>1,'premium_plus'=>2];
                $currentOrder = $tierOrder[$currentTier] ?? 0;
                $planOrder    = $tierOrder[$key] ?? 0;
                if ($isCurrent): ?>
                    <div class="btn btn-<?= $plan['color'] ?> w-100 fw-bold disabled">ACTIF</div>
                <?php elseif ($planOrder < $currentOrder): ?>
                    <div class="btn btn-outline-secondary w-100 disabled" title="Tu as deja un forfait superieur">Non disponible</div>
                <?php elseif ($key === 'free'): ?>
                    <div class="btn btn-outline-secondary w-100 disabled">Non disponible</div>
                <?php else: ?>
                    <a href="upgrade.php?plan=<?= $key ?>" class="btn btn-<?= $plan['color'] ?> w-100 fw-bold">CHOISIR</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

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