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

requireLogin();
$user = getConnectedUser($pdo);
if (!$user || (!isAdmin($user) && !(int)($user['is_admin_store'] ?? 0))) {
    header("Location: index.php"); exit;
}
$userId = (int)$user['id'];
$msg = ''; $error = '';

// --- ACTIONS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Sauvegarder les infos boutique
    if (isset($_POST['save_settings'])) {
        $storeName     = trim(htmlspecialchars($_POST['store_name']     ?? ''));
        $paypalEmail   = trim(htmlspecialchars($_POST['paypal_email']   ?? ''));
        $taxCA         = (float)($_POST['tax_canada']  ?? 5.00);
        $taxQC         = (float)($_POST['tax_quebec']  ?? 9.975);
        $returnPolicy  = trim(htmlspecialchars($_POST['return_policy']  ?? ''));
        $warrantyDays  = max(0,(int)($_POST['warranty_days'] ?? 0));
        $logoPath      = null;

        if (isset($_FILES['logo']) && $_FILES['logo']['size'] > 0) {
            $f   = $_FILES['logo'];
            $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
            if (in_array($ext,['png','jpg','jpeg','gif','webp','svg'])) {
                $dir = __DIR__ . '/uploads/store/';
                if (!is_dir($dir)) mkdir($dir,0755,true);
                $fname = 'logo_'.time().'.'.$ext;
                if (move_uploaded_file($f['tmp_name'],$dir.$fname)) $logoPath = 'uploads/store/'.$fname;
            }
        }

        $exists = $pdo->query("SELECT id FROM store_settings WHERE id=1")->fetch();
        if ($exists) {
            $sql = "UPDATE store_settings SET store_name=?,paypal_email=?,tax_canada=?,tax_quebec=?,return_policy=?,warranty_days=?" . ($logoPath?",logo_path=?":'') . " WHERE id=1";
            $params = [$storeName,$paypalEmail,$taxCA,$taxQC,$returnPolicy,$warrantyDays];
            if ($logoPath) $params[] = $logoPath;
        } else {
            $sql = "INSERT INTO store_settings (id,store_name,paypal_email,tax_canada,tax_quebec,return_policy,warranty_days,logo_path) VALUES (1,?,?,?,?,?,?,?)";
            $params = [$storeName,$paypalEmail,$taxCA,$taxQC,$returnPolicy,$warrantyDays,$logoPath??''];
        }
        $pdo->prepare($sql)->execute($params);
        $msg = "Paramètres boutique sauvegardés !";
    }

    // Ajouter un article
    if (isset($_POST['add_item'])) {
        $name     = trim(htmlspecialchars($_POST['name']     ?? ''));
        $desc     = trim(htmlspecialchars($_POST['description'] ?? ''));
        $price    = max(0,(float)$_POST['price']);
        $salePr   = max(0,(float)($_POST['sale_price'] ?? 0));
        $priceJetons = max(0,(int)($_POST['price_jetons'] ?? 0));
        try { $pdo->exec("ALTER TABLE store_items ADD COLUMN IF NOT EXISTS price_jetons INT DEFAULT 0"); } catch(Exception $e) {}
        $onSale   = isset($_POST['is_on_sale']) ? 1 : 0;
        $itemType = trim(htmlspecialchars($_POST['item_type'] ?? ''));
        $sku      = trim(htmlspecialchars($_POST['sku']      ?? ''));
        $photoPath = null;

        if (isset($_FILES['photo']) && $_FILES['photo']['size'] > 0) {
            $f   = $_FILES['photo'];
            $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
            if (in_array($ext,['png','jpg','jpeg','gif','webp'])) {
                $dir = __DIR__ . '/uploads/store/items/';
                if (!is_dir($dir)) mkdir($dir,0755,true);
                $fname = 'item_'.time().'_'.rand(100,999).'.'.$ext;
                if (move_uploaded_file($f['tmp_name'],$dir.$fname)) $photoPath = 'uploads/store/items/'.$fname;
            }
        }

        if ($name && $price > 0) {
            $pdo->prepare("INSERT INTO store_items (owner_id,name,description,price,sale_price,is_on_sale,item_type,sku,photo_path) VALUES (?,?,?,?,?,?,?,?,?)")
                ->execute([$userId,$name,$desc,$price,$salePr,$onSale,$itemType,$sku,$photoPath]);
            $msg = "Article ajouté !";
        } else { $error = "Nom et prix requis."; }
    }

    // Modifier un article
    if (isset($_POST['edit_item'])) {
        $itemId   = (int)$_POST['item_id'];
        $name     = trim(htmlspecialchars($_POST['name']));
        $desc     = trim(htmlspecialchars($_POST['description']));
        $price    = max(0,(float)$_POST['price']);
        $salePr   = max(0,(float)($_POST['sale_price'] ?? 0));
        $priceJetons = max(0,(int)($_POST['price_jetons'] ?? 0));
        try { $pdo->exec("ALTER TABLE store_items ADD COLUMN IF NOT EXISTS price_jetons INT DEFAULT 0"); } catch(Exception $e) {}
        $onSale   = isset($_POST['is_on_sale']) ? 1 : 0;
        $itemType = trim(htmlspecialchars($_POST['item_type'] ?? ''));
        $sku      = trim(htmlspecialchars($_POST['sku'] ?? ''));
        $pdo->prepare("UPDATE store_items SET name=?,description=?,price=?,sale_price=?,is_on_sale=?,item_type=?,sku=? WHERE id=?")
            ->execute([$name,$desc,$price,$salePr,$onSale,$itemType,$sku,$itemId]);
        $msg = "Article modifié.";
    }

    // Supprimer un article
    if (isset($_POST['delete_item'])) {
        $pdo->prepare("DELETE FROM store_items WHERE id=?")->execute([(int)$_POST['item_id']]);
        $msg = "Article supprimé.";
    }
}

$settings = $pdo->query("SELECT * FROM store_settings WHERE id=1")->fetch();
$items    = $pdo->prepare("SELECT * FROM store_items WHERE owner_id=? ORDER BY id DESC");
$items->execute([$userId]);
$myItems  = $items->fetchAll();

include 'header.php';
?>

<div class="container-fluid mt-4 px-4">
    <h5 class="oracle-text text-success mb-3"> GESTION MA BOUTIQUE</h5>

    <?php if ($msg):   ?><div class="alert alert-success small py-2"><?= $msg ?></div>
                <div class="mb-3">
                    <label class="fw-bold text-warning mb-1" style="font-size:0.75rem;">Prix en jetons <span class="text-muted" style="font-size:0.65rem;font-weight:normal;">(0 = non disponible en jetons)</span></label>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text bg-dark border-secondary" style="color:#ffc107;">&#9670;</span>
                        <input type="number" name="price_jetons" min="0" step="1" value="<?= (int)($editItem['price_jetons'] ?? 0) ?>"
                               class="form-control bg-dark text-white border-secondary">
                    </div>
                </div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger  small py-2"><?= $error ?></div><?php endif; ?>

    <div class="row g-4">

        <!-- Paramètres boutique -->
        <div class="col-md-4">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header bg-secondary text-white py-2 fw-bold small">⚙️ PARAMÈTRES</div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <div class="mb-2">
                            <label class="small text-white d-block mb-1">Nom de la boutique</label>
                            <input type="text" name="store_name" class="form-control form-control-sm"
                                   placeholder="Ex: La Boutique de Pascal"
                                   value="<?= htmlspecialchars($settings['store_name'] ?? '') ?>" required>
                        </div>
                        <div class="mb-2">
                            <label class="small text-white d-block mb-1">Logo (image)</label>
                            <input type="file" name="logo" class="form-control form-control-sm" accept="image/*">
                            <?php if (!empty($settings['logo_path'])): ?>
                                <img src="<?= htmlspecialchars($settings['logo_path']) ?>" style="height:30px;margin-top:4px;">
                            <?php endif; ?>
                        </div>
                        <div class="mb-2">
                            <label class="small text-white d-block mb-1">Courriel PayPal</label>
                            <input type="email" name="paypal_email" class="form-control form-control-sm"
                                   placeholder="paypal@email.com"
                                   value="<?= htmlspecialchars($settings['paypal_email'] ?? '') ?>">
                        </div>
                        <div class="row g-2 mb-2">
                            <div class="col-6">
                                <label class="small text-white d-block mb-1">Taxe Canada (%)</label>
                                <input type="number" name="tax_canada" class="form-control form-control-sm" step="0.01"
                                       value="<?= $settings['tax_canada'] ?? '5.00' ?>">
                            </div>
                            <div class="col-6">
                                <label class="small text-white d-block mb-1">Taxe Québec (%)</label>
                                <input type="number" name="tax_quebec" class="form-control form-control-sm" step="0.001"
                                       value="<?= $settings['tax_quebec'] ?? '9.975' ?>">
                            </div>
                        </div>
                        <div class="mb-2">
                            <label class="small text-white d-block mb-1">Garantie (jours)</label>
                            <input type="number" name="warranty_days" class="form-control form-control-sm" min="0"
                                   value="<?= $settings['warranty_days'] ?? '0' ?>">
                        </div>
                        <div class="mb-3">
                            <label class="small text-white d-block mb-1">Politique de retour</label>
                            <textarea name="return_policy" class="form-control form-control-sm" rows="3"
                                      placeholder="Ex: Retours acceptés dans les 30 jours…"><?= htmlspecialchars($settings['return_policy'] ?? '') ?></textarea>
                        </div>
                        <button type="submit" name="save_settings" class="btn btn-success btn-sm w-100 fw-bold">SAUVEGARDER</button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Ajouter un article + liste -->
        <div class="col-md-8">
            <!-- Formulaire ajout -->
            <div class="card bg-dark border-success shadow mb-3">
                <div class="card-header bg-success text-white py-2 fw-bold small">➕ NOUVEL ARTICLE</div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <div class="row g-2">
                            <div class="col-md-6">
                                <label class="small text-white d-block mb-1">Nom de l'article</label>
                                <input type="text" name="name" class="form-control form-control-sm" placeholder="Ex: Chandail XL" required>
                            </div>
                            <div class="col-md-3">
                                <label class="small text-white d-block mb-1">Prix ($)</label>
                                <input type="number" name="price" class="form-control form-control-sm" step="0.01" min="0" placeholder="Ex: 29.99" required>
                            </div>
                            <div class="col-md-3">
                                <label class="small text-white d-block mb-1">Prix vente ($)</label>
                                <input type="number" name="sale_price" class="form-control form-control-sm" step="0.01" min="0" placeholder="Ex: 19.99">
                            </div>
                            <div class="col-12">
                                <label class="small text-white d-block mb-1">Description</label>
                                <textarea name="description" class="form-control form-control-sm" rows="2" placeholder="Décris l'article…"></textarea>
                            </div>
                            <div class="col-md-4">
                                <label class="small text-white d-block mb-1">Type d'article</label>
                                <input type="text" name="item_type" class="form-control form-control-sm" placeholder="Ex: Vêtement">
                            </div>
                            <div class="col-md-4">
                                <label class="small text-white d-block mb-1">Numéro d'article (SKU)</label>
                                <input type="text" name="sku" class="form-control form-control-sm" placeholder="Ex: CHN-XL-001">
                            </div>
                            <div class="col-md-4">
                                <label class="small text-white d-block mb-1">Photo</label>
                                <input type="file" name="photo" class="form-control form-control-sm" accept="image/*">
                            </div>
                            <div class="col-12">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="is_on_sale" id="onSaleChk">
                                    <label class="form-check-label small text-danger" for="onSaleChk">EN VENTE (utiliser le prix vente)</label>
                                </div>
                            </div>
                        </div>
                        <div class="text-end mt-2">
                            <button type="submit" name="add_item" class="btn btn-success btn-sm fw-bold px-4">AJOUTER</button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Liste mes articles -->
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header bg-secondary text-white py-2 fw-bold small"> MES ARTICLES (<?= count($myItems) ?>)</div>
                <div class="table-responsive">
                    <table class="table table-dark table-hover table-sm small mb-0">
                        <thead><tr><th>Photo</th><th>Nom</th><th>Type</th><th class="text-center">Prix</th><th class="text-center">Vente</th><th></th></tr></thead>
                        <tbody>
                        <?php if (empty($myItems)): ?>
                            <tr><td colspan="6" class="text-center text-muted py-3">Aucun article.</td></tr>
                        <?php endif; ?>
                        <?php foreach ($myItems as $it): ?>
                        <tr>
                            <td>
                                <?php if (!empty($it['photo_path'])): ?>
                                    <img src="<?= htmlspecialchars($it['photo_path']) ?>" style="width:32px;height:32px;object-fit:cover;border-radius:3px;">
                                <?php else: ?><?php endif; ?>
                            </td>
                            <td>
                                <strong><?= htmlspecialchars($it['name']) ?></strong>
                                <?php if (!empty($it['sku'])): ?><br><small class="text-muted"><?= htmlspecialchars($it['sku']) ?></small><?php endif; ?>
                            </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'] && $it['sale_price']): ?>
                                    <span class="text-danger"><?= number_format((float)$it['sale_price'],2) ?>$</span>
                                <?php else: ?>—<?php endif; ?>
                            </td>
                            <td class="text-center">
                                <button class="btn btn-xs btn-outline-warning py-0" data-bs-toggle="modal" data-bs-target="#editItem<?= $it['id'] ?>"><i class="fa-solid fa-gear" style="font-size:0.6rem;"></i></button>
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="item_id" value="<?= $it['id'] ?>">
                                    <button type="submit" name="delete_item" class="btn btn-xs btn-outline-danger py-0"
                                            onclick="return confirm('Supprimer cet article ?')">X️</button>
                                </form>
                            </td>
                        </tr>
                        <!-- Modal edit article -->
                        <div class="modal fade" id="editItem<?= $it['id'] ?>" tabindex="-1" aria-hidden="true">
                            <div class="modal-dialog modal-sm modal-dialog-centered">
                                <div class="modal-content bg-dark border-warning text-white">
                                    <div class="modal-header border-secondary py-2">
                                        <h6 class="modal-title text-warning small">✏️ <?= htmlspecialchars($it['name']) ?></h6>
                                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                    </div>
                                    <form method="POST">
                                        <input type="hidden" name="item_id" value="<?= $it['id'] ?>">
                                        <div class="modal-body p-3">
                                            <div class="mb-2">
                                                <label class="small text-white d-block mb-1">Nom</label>
                                                <input type="text" name="name" class="form-control form-control-sm" value="<?= htmlspecialchars($it['name']) ?>" required>
                                            </div>
                                            <div class="mb-2">
                                                <label class="small text-white d-block mb-1">Description</label>
                                                <textarea name="description" class="form-control form-control-sm" rows="2"><?= htmlspecialchars($it['description']??'') ?></textarea>
                                            </div>
                                            <div class="row g-2 mb-2">
                                                <div class="col-6">
                                                    <label class="small text-white d-block mb-1">Prix ($)</label>
                                                    <input type="number" name="price" class="form-control form-control-sm" step="0.01" value="<?= $it['price'] ?>" required>
                                                </div>
                                                <div class="col-6">
                                                    <label class="small text-white d-block mb-1">Prix vente ($)</label>
                                                    <input type="number" name="sale_price" class="form-control form-control-sm" step="0.01" value="<?= $it['sale_price']??0 ?>">
                                                </div>
                                            </div>
                                            <div class="row g-2 mb-2">
                                                <div class="col-6">
                                                    <label class="small text-white d-block mb-1">Type</label>
                                                    <input type="text" name="item_type" class="form-control form-control-sm" value="<?= htmlspecialchars($it['item_type']??'') ?>">
                                                </div>
                                                <div class="col-6">
                                                    <label class="small text-white d-block mb-1">SKU</label>
                                                    <input type="text" name="sku" class="form-control form-control-sm" value="<?= htmlspecialchars($it['sku']??'') ?>">
                                                </div>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="is_on_sale" id="sale<?= $it['id'] ?>" <?= $it['is_on_sale']?'checked':'' ?>>
                                                <label class="form-check-label small text-danger" for="sale<?= $it['id'] ?>">En vente</label>
                                            </div>
                                        </div>
                                        <div class="modal-footer border-secondary py-2">
                                            <button type="submit" name="edit_item" class="btn btn-warning btn-sm fw-bold w-100">ENREGISTRER</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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