<?php
require_once __DIR__ . '/includes/admin_bootstrap.php';
$msg    = '';
$action = $_GET['action'] ?? 'list';
$editId = (int)($_GET['id'] ?? 0);

// ── Delete ──
if ($action==='delete' && $editId) {
    $pdo->prepare("DELETE FROM coupons WHERE id=?")->execute([$editId]);
    redirect(BASE_URL.'/admin/coupons.php?deleted=1');
}

// ── Toggle active ──
if ($action==='toggle' && $editId) {
    $pdo->prepare("UPDATE coupons SET is_active=1-is_active WHERE id=?")->execute([$editId]);
    redirect(BASE_URL.'/admin/coupons.php');
}

// ── Save ──
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_coupon'])) {
    $code        = strtoupper(trim($_POST['code'] ?? ''));
    $type        = $_POST['discount_type'] ?? 'percent';
    $value       = (float)($_POST['discount_value'] ?? 0);
    $minOrder    = (float)($_POST['min_order_amount'] ?? 0);
    $maxDiscount = (float)($_POST['max_discount'] ?? 0);
    $usageLimit  = (int)($_POST['usage_limit'] ?? 0);
    $expiry      = $_POST['expiry_date'] ?? '';
    $isActive    = isset($_POST['is_active']) ? 1 : 0;
    $cid         = (int)($_POST['coupon_id'] ?? 0);

    if (!$code || $value <= 0) {
        $msg='<div class="alert alert-error">কুপন কোড ও ডিসকাউন্ট মান আবশ্যক।</div>';
    } else {
        // Check duplicate code
        $chk=$pdo->prepare("SELECT id FROM coupons WHERE code=? AND id!=?");
        $chk->execute([$code,$cid]);
        if($chk->fetch()){
            $msg='<div class="alert alert-error">এই কুপন কোড ইতিমধ্যে আছে।</div>';
        } else {
            $expiryVal = $expiry ?: null;
            if($cid){
                $pdo->prepare("UPDATE coupons SET code=?,discount_type=?,discount_value=?,min_order_amount=?,max_discount=?,usage_limit=?,expiry_date=?,is_active=? WHERE id=?")
                    ->execute([$code,$type,$value,$minOrder,$maxDiscount,$usageLimit,$expiryVal,$isActive,$cid]);
            } else {
                $pdo->prepare("INSERT INTO coupons(code,discount_type,discount_value,min_order_amount,max_discount,usage_limit,expiry_date,is_active) VALUES(?,?,?,?,?,?,?,?)")
                    ->execute([$code,$type,$value,$minOrder,$maxDiscount,$usageLimit,$expiryVal,$isActive]);
            }
            $msg='<div class="alert alert-success"><i class="fas fa-check-circle"></i> কুপন সংরক্ষণ সফল।</div>';
            $action='list'; $editId=0;
        }
    }
}

$coupons = $pdo->query("SELECT * FROM coupons ORDER BY created_at DESC")->fetchAll();
$editing = null;
if ($editId && $action==='edit') {
    $es=$pdo->prepare("SELECT * FROM coupons WHERE id=?"); $es->execute([$editId]); $editing=$es->fetch();
}

include __DIR__ . '/includes/admin_header.php';
?>
<h2>কুপন ব্যবস্থাপনা</h2>
<?= $msg ?>
<?php if(isset($_GET['deleted'])): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> কুপন মুছে ফেলা হয়েছে।</div><?php endif; ?>

<div style="display:grid;grid-template-columns:1fr 380px;gap:20px;align-items:start;">

    <!-- Coupon List -->
    <div class="card">
        <div class="card-header">
            <h3><i class="fas fa-ticket-alt"></i> সকল কুপন</h3>
            <a href="?action=add" class="topbar-btn btn-gold"><i class="fas fa-plus"></i> নতুন কুপন</a>
        </div>
        <div class="table-wrap">
            <table>
                <thead><tr>
                    <th>কোড</th><th>ধরন</th><th>মান</th><th>সর্বনিম্ন অর্ডার</th>
                    <th>ব্যবহার</th><th>মেয়াদ</th><th>অবস্থা</th><th>অ্যাকশন</th>
                </tr></thead>
                <tbody>
                <?php foreach($coupons as $c): ?>
                <tr>
                    <td><strong style="font-family:monospace;color:var(--navy);letter-spacing:1px;"><?=e($c['code'])?></strong></td>
                    <td><?=$c['discount_type']==='percent'?'শতকরা (%)':'নির্দিষ্ট (৳)'?></td>
                    <td><?=$c['discount_type']==='percent'?$c['discount_value'].'%':'৳'.number_format($c['discount_value'],0)?></td>
                    <td>৳<?=number_format($c['min_order_amount'],0)?></td>
                    <td style="font-size:.82rem;">
                        <?=$c['used_count']?>/<?=$c['usage_limit']?:'∞'?>
                    </td>
                    <td style="font-size:.82rem;">
                        <?php if($c['expiry_date']): ?>
                            <?= date('d/m/Y',strtotime($c['expiry_date'])) ?>
                            <?php if(strtotime($c['expiry_date'])<time()): ?>
                                <span class="badge badge-cancelled">মেয়াদ শেষ</span>
                            <?php endif; ?>
                        <?php else: ?>
                            <span style="color:var(--g400);">সীমাহীন</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="badge <?=$c['is_active']?'badge-active':'badge-inactive'?>">
                            <?=$c['is_active']?'সক্রিয়':'নিষ্ক্রিয়'?>
                        </span>
                    </td>
                    <td>
                        <div class="actions">
                            <a href="?action=edit&id=<?=$c['id']?>" class="topbar-btn btn-navy" title="সম্পাদনা"><i class="fas fa-edit"></i></a>
                            <a href="?action=toggle&id=<?=$c['id']?>" class="topbar-btn btn-gray" title="চালু/বন্ধ"><i class="fas fa-toggle-<?=$c['is_active']?'on':'off'?>"></i></a>
                            <a href="?action=delete&id=<?=$c['id']?>" class="topbar-btn btn-red" data-confirm="এই কুপন মুছে ফেলবেন?" title="মুছুন"><i class="fas fa-trash"></i></a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if(empty($coupons)): ?>
                    <tr><td colspan="8" style="text-align:center;padding:28px;color:var(--g400);">কোনো কুপন নেই।</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Add/Edit Form -->
    <div class="card">
        <div class="card-header">
            <h3><?= $editing?'কুপন সম্পাদনা':'নতুন কুপন তৈরি' ?></h3>
            <?php if($editing): ?><a href="?" class="topbar-btn btn-gray">বাতিল</a><?php endif; ?>
        </div>
        <div class="card-body">
            <form method="POST">
                <input type="hidden" name="coupon_id" value="<?=$editing['id']??0?>">

                <div class="form-group">
                    <label class="form-label">কুপন কোড *</label>
                    <input type="text" class="form-control" name="code"
                           value="<?=e($editing['code']??'')?>"
                           placeholder="যেমন: EID20, SAVE50"
                           style="text-transform:uppercase;font-family:monospace;letter-spacing:2px;"
                           oninput="this.value=this.value.toUpperCase()" required>
                    <div class="form-hint">বড় হাতের অক্ষরে স্বয়ংক্রিয় হবে</div>
                </div>

                <div class="form-group">
                    <label class="form-label">ডিসকাউন্টের ধরন *</label>
                    <select class="form-control" name="discount_type" id="discType" onchange="toggleMaxDiscount()">
                        <option value="percent" <?=($editing['discount_type']??'percent')==='percent'?'selected':''?>>শতকরা (%)</option>
                        <option value="fixed"   <?=($editing['discount_type']??'')==='fixed'?'selected':''?>>নির্দিষ্ট পরিমাণ (৳)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label class="form-label">ডিসকাউন্ট মান *</label>
                    <input type="number" class="form-control" name="discount_value"
                           value="<?=$editing['discount_value']??''?>" min="0.01" step="0.01" required>
                    <div class="form-hint">শতকরা হলে ০–১০০, নির্দিষ্ট হলে টাকার পরিমাণ</div>
                </div>

                <div class="form-group" id="maxDiscountGroup" style="<?=($editing['discount_type']??'percent')==='percent'?'':'display:none'?>">
                    <label class="form-label">সর্বোচ্চ ডিসকাউন্ট (৳) <span style="color:var(--g400);">(ঐচ্ছিক)</span></label>
                    <input type="number" class="form-control" name="max_discount"
                           value="<?=$editing['max_discount']??0?>" min="0" step="0.01">
                    <div class="form-hint">0 মানে কোনো সীমা নেই</div>
                </div>

                <div class="form-group">
                    <label class="form-label">সর্বনিম্ন অর্ডার পরিমাণ (৳)</label>
                    <input type="number" class="form-control" name="min_order_amount"
                           value="<?=$editing['min_order_amount']??0?>" min="0" step="0.01">
                    <div class="form-hint">0 মানে কোনো সীমা নেই</div>
                </div>

                <div class="form-group">
                    <label class="form-label">ব্যবহারের সীমা</label>
                    <input type="number" class="form-control" name="usage_limit"
                           value="<?=$editing['usage_limit']??0?>" min="0">
                    <div class="form-hint">0 মানে সীমাহীন</div>
                </div>

                <div class="form-group">
                    <label class="form-label">মেয়াদ শেষের তারিখ</label>
                    <input type="date" class="form-control" name="expiry_date"
                           value="<?=$editing['expiry_date']??''?>">
                    <div class="form-hint">ফাঁকা রাখলে মেয়াদ থাকবে না</div>
                </div>

                <div class="form-group">
                    <label class="form-check">
                        <input type="checkbox" name="is_active" value="1"
                               <?=($editing['is_active']??1)?'checked':''?>>
                        <span>সক্রিয়</span>
                    </label>
                </div>

                <button type="submit" name="save_coupon" class="topbar-btn btn-gold" style="width:100%;justify-content:center;padding:11px;">
                    <i class="fas fa-save"></i> কুপন সংরক্ষণ করুন
                </button>
            </form>
        </div>
    </div>
</div>

<script>
function toggleMaxDiscount(){
    var t=document.getElementById('discType').value;
    document.getElementById('maxDiscountGroup').style.display=t==='percent'?'':'none';
}
</script>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
