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

requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

$msg = '';

// Actions admin boutique
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_sale_status'])) {
        $saleId    = trim(htmlspecialchars($_POST['sale_id'] ?? ''));
        $newStatus = in_array($_POST['new_status'],['cart','paid','refunded','pending']) ? $_POST['new_status'] : 'pending';
        $pdo->prepare("UPDATE store_sales SET status=? WHERE transaction_id=?")->execute([$newStatus,$saleId]);
        $msg = "Transaction #{$saleId} → " . strtoupper($newStatus);
    }
    if (isset($_POST['delete_item_admin'])) {
        $pdo->prepare("DELETE FROM store_items WHERE id=?")->execute([(int)$_POST['item_id']]);
        $msg = "Article supprimé.";
    }
    if (isset($_POST['toggle_sale_admin'])) {
        $itemId = (int)$_POST['item_id'];
        $newVal = (int)$_POST['new_on_sale'];
        $pdo->prepare("UPDATE store_items SET is_on_sale=? WHERE id=?")->execute([$newVal,$itemId]);
        $msg = "Statut vente mis à jour.";
    }
}

// Chiffres globaux
$nbItems = $pdo->query("SELECT COUNT(*) FROM store_items")->fetchColumn();
$nbSales = $pdo->query("SELECT COUNT(*) FROM store_sales WHERE status='paid'")->fetchColumn();
$revenue = $pdo->query("SELECT SUM(total_price) FROM store_sales WHERE status='paid'")->fetchColumn() ?? 0;

$items = $pdo->query("SELECT si.*, u.username as owner_name FROM store_items si LEFT JOIN users u ON u.id=si.owner_id ORDER BY si.id DESC")->fetchAll();
try {
    $sales = $pdo->query("SELECT ss.*, u.username FROM store_sales ss LEFT JOIN users u ON u.id=ss.user_id ORDER BY ss.id DESC LIMIT 50")->fetchAll();
} catch (Exception $e) { $sales = []; }

include 'header.php';
?>

<div class="container-fluid mt-4 px-4">
    <a href="admin.php" class="btn btn-outline-secondary btn-sm mb-3">&larr; Admin</a>
    <h5 class="oracle-text text-success mb-3"> ADMIN — BOUTIQUE</h5>

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

    <!-- Stats -->
    <div class="row g-3 mb-4">
        <div class="col-md-3"><div class="card bg-dark border-success text-center p-3"><div class="text-success fw-bold" style="font-size:1.5rem;"><?= $nbItems ?></div><small class="text-muted">Articles</small></div></div>
        <div class="col-md-3"><div class="card bg-dark border-primary text-center p-3"><div class="text-primary fw-bold" style="font-size:1.5rem;"><?= $nbSales ?></div><small class="text-muted">Ventes payées</small></div></div>
        <div class="col-md-3"><div class="card bg-dark border-warning text-center p-3"><div class="text-warning fw-bold" style="font-size:1.5rem;"><?= number_format((float)$revenue,2) ?>$</div><small class="text-muted">Revenus</small></div></div>
        <div class="col-md-3"><div class="card bg-dark border-info text-center p-3 d-flex flex-column align-items-center justify-content-center">
            <a href="store_manage.php" class="btn btn-outline-success btn-sm mb-1">⚙️ Ma boutique</a>
            <a href="store.php"        class="btn btn-outline-secondary btn-sm">️ Voir boutique</a>
        </div></div>
    </div>

    <!-- Tous les articles -->
    <div class="card bg-dark border-secondary shadow mb-4">
        <div class="card-header bg-secondary text-white py-2 fw-bold small"> TOUS LES ARTICLES</div>
        <div class="table-responsive">
            <table class="table table-dark table-hover table-sm small mb-0">
                <thead><tr><th>#</th><th>Nom</th><th>Vendeur</th><th>Type</th><th class="text-center">Prix</th><th class="text-center">Vente</th><th class="text-center">Actions</th></tr></thead>
                <tbody>
                <?php foreach ($items as $it): ?>
                <tr class="<?= $it['is_on_sale']?'table-warning':'' ?>">
                    <td><?= $it['id'] ?></td>
                    <td><strong><?= htmlspecialchars($it['name']) ?></strong></td>
                    <td class="text-info"><?= htmlspecialchars($it['owner_name'] ?? '—') ?></td>
                    <td class="text-muted"><?= htmlspecialchars($it['item_type']??'—') ?></td>
                    <td class="text-center text-success"><?= number_format((float)$it['price'],2) ?>$</td>
                    <td class="text-center">
                        <?php if ($it['is_on_sale']): ?>
                            <span class="text-danger"><?= number_format((float)$it['sale_price'],2) ?>$</span>
                        <?php else: ?>—<?php endif; ?>
                    </td>
                    <td class="text-center d-flex gap-1 justify-content-center">
                        <form method="POST" class="d-inline">
                            <input type="hidden" name="item_id"   value="<?= $it['id'] ?>">
                            <input type="hidden" name="new_on_sale" value="<?= $it['is_on_sale']?0:1 ?>">
                            <button type="submit" name="toggle_sale_admin" class="btn btn-xs btn-outline-warning py-0">
                                <?= $it['is_on_sale']?'▼ Normal':'▲ Solde' ?>
                            </button>
                        </form>
                        <form method="POST" class="d-inline">
                            <input type="hidden" name="item_id" value="<?= $it['id'] ?>">
                            <button type="submit" name="delete_item_admin" class="btn btn-xs btn-outline-danger py-0"
                                    onclick="return confirm('Supprimer ?')">X️</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Transactions -->
    <div class="card bg-dark border-secondary shadow">
        <div class="card-header bg-secondary text-white py-2 fw-bold small"> TRANSACTIONS RÉCENTES</div>
        <div class="table-responsive">
            <table class="table table-dark table-hover table-sm small mb-0">
                <thead><tr><th>Transaction</th><th>Acheteur</th><th>Article</th><th class="text-center">Total</th><th class="text-center">Taxes</th><th class="text-center">Statut</th><th class="text-center">Action</th></tr></thead>
                <tbody>
                <?php if (empty($sales)): ?>
                    <tr><td colspan="7" class="text-center text-muted py-3">Aucune transaction.</td></tr>
                <?php endif; ?>
                <?php foreach ($sales as $s):
                    // Support deux formats: ancien (item_id) et nouveau (items_json)
                    $saleRef = $s['transaction_id'] ?? $s['id'] ?? '—';
                    $saleDate = $s['sale_date'] ?? $s['created_at'] ?? null;
                    $itemDisplay = '—';
                    if (!empty($s['items_json'])) {
                        $items = json_decode($s['items_json'], true);
                        if ($items) $itemDisplay = implode(', ', array_column($items, 'name'));
                    } elseif (!empty($s['item_name'])) {
                        $itemDisplay = $s['item_name'];
                    }
                ?>
                <tr>
                    <td class="text-muted" style="font-size:0.6rem;">#<?= $saleRef ?></td>
                    <td><?= htmlspecialchars($s['username'] ?? '—') ?></td>
                    <td style="font-size:0.7rem;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?= htmlspecialchars($itemDisplay) ?>"><?= htmlspecialchars(mb_substr($itemDisplay,0,30)) ?></td>
                    <td class="text-center text-success"><?= number_format((float)($s['total_price']??0),2) ?>$</td>
                    <td class="text-center text-muted" style="font-size:0.62rem;">
                        <?= $saleDate ? date('d M H:i', strtotime($saleDate)) : '—' ?>
                    </td>
                    <td class="text-center">
                        <span class="badge bg-<?= match($s['status']??''){'paid'=>'success','cart'=>'secondary','refunded'=>'warning text-dark',default=>'info text-dark'} ?>" style="font-size:0.55rem;">
                            <?= strtoupper($s['status'] ?? 'PAID') ?>
                        </span>
                    </td>
                    <td class="text-center">
                        <form method="POST" class="d-flex gap-1 justify-content-center">
                            <input type="hidden" name="sale_id" value="<?= $saleRef ?>">
                            <select name="new_status" class="form-select form-select-sm" style="width:90px;font-size:0.65rem;">
                                <option value="paid"     <?= ($s['status']??'')==='paid'?'selected':'' ?>>Paye</option>
                                <option value="pending"  <?= ($s['status']??'')==='pending'?'selected':'' ?>>En attente</option>
                                <option value="refunded" <?= ($s['status']??'')==='refunded'?'selected':'' ?>>Rembourse</option>
                                <option value="cancelled" <?= ($s['status']??'')==='cancelled'?'selected':'' ?>>Annule</option>
                            </select>
                            <button type="submit" name="update_sale_status" class="btn btn-xs btn-warning py-0">OK</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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