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

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

if($_SERVER['REQUEST_METHOD']==='POST'&&isset($_POST['save_coupon'])){
    $code=strtoupper(trim($_POST['code']??''));$type=$_POST['discount_type']??'percent';
    $val=(float)($_POST['discount_value']??0);$minOrd=(float)($_POST['min_order_amount']??0);
    $maxDis=(float)($_POST['max_discount']??0);$usageLim=(int)($_POST['usage_limit']??0);
    $expiry=$_POST['expiry_date']??'';$active=isset($_POST['is_active'])?1:0;
    $reqLogin=isset($_POST['require_login'])?1:0;
    $assignedUser=(int)($_POST['assigned_user_id']??0);
    $cid=(int)($_POST['coupon_id']??0);
    if(!$code||$val<=0){$msg='<div class="alert alert-error">কোড ও মান আবশ্যক।</div>';}
    else{
        $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{
            $ex=$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=?,require_login=?,assigned_user_id=? WHERE id=?")->execute([$code,$type,$val,$minOrd,$maxDis,$usageLim,$ex,$active,$reqLogin,$assignedUser?:null,$cid]);
            else $pdo->prepare("INSERT INTO coupons(code,discount_type,discount_value,min_order_amount,max_discount,usage_limit,expiry_date,is_active,require_login,assigned_user_id)VALUES(?,?,?,?,?,?,?,?,?,?)")->execute([$code,$type,$val,$minOrd,$maxDis,$usageLim,$ex,$active,$reqLogin,$assignedUser?:null]);
            $msg='<div class="alert alert-success"><i class="fas fa-check-circle"></i> কুপন সংরক্ষণ সফল।</div>';$action='list';$editId=0;
        }
    }
}

$coupons=$pdo->query("SELECT c.*,u.name as user_name FROM coupons c LEFT JOIN users u ON c.assigned_user_id=u.id ORDER BY c.created_at DESC")->fetchAll();
$users=$pdo->query("SELECT id,name,phone FROM users WHERE role='user' ORDER BY name")->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">কুপন মুছে ফেলা হয়েছে।</div><?php endif;?>

<div style="display:grid;grid-template-columns:1fr 380px;gap:20px;align-items:start;">
    <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><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'?$c['discount_value'].'%':'৳'.(int)$c['discount_value']?></td>
                    <td style="font-size:.82rem;">সর্বনিম্ন: ৳<?=(int)$c['min_order_amount']?></td>
                    <td style="font-size:.82rem;"><?=$c['used_count']?>/<?=$c['usage_limit']?:'∞'?></td>
                    <td><?=$c['require_login']?'<span class="badge badge-active">হ্যাঁ</span>':'<span class="badge badge-inactive">না</span>'?></td>
                    <td style="font-size:.82rem;"><?=$c['user_name']?e($c['user_name']):'<span style="color:var(--g400);">সবার জন্য</span>'?></td>
                    <td style="font-size:.8rem;"><?=$c['expiry_date']?date('d/m/Y',strtotime($c['expiry_date'])):'∞'?></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"><i class="fas fa-edit"></i></a>
                        <a href="?action=toggle&id=<?=$c['id']?>" class="topbar-btn btn-gray"><i class="fas fa-power-off"></i></a>
                        <a href="?action=delete&id=<?=$c['id']?>" class="topbar-btn btn-red" data-confirm="মুছবেন?"><i class="fas fa-trash"></i></a>
                    </div></td>
                </tr>
                <?php endforeach;?>
                <?php if(empty($coupons)):?><tr><td colspan="9" style="text-align:center;padding:24px;color:var(--g400);">কোনো কুপন নেই।</td></tr><?php endif;?>
                </tbody>
            </table>
        </div>
    </div>

    <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" style="text-transform:uppercase;font-family:monospace;letter-spacing:2px;" oninput="this.value=this.value.toUpperCase()" required>
                </div>
                <div class="form-group">
                    <label class="form-label">ডিসকাউন্টের ধরন</label>
                    <select class="form-control" name="discount_type" id="discType" onchange="toggleMax()">
                        <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>
                <div class="form-group" id="maxG" style="<?=($editing['discount_type']??'percent')==='percent'?'':'display:none'?>">
                    <label class="form-label">সর্বোচ্চ ছাড় (৳) <small style="color:var(--g400);">0=সীমাহীন</small></label>
                    <input type="number" class="form-control" name="max_discount" value="<?=$editing['max_discount']??0?>" min="0" step="0.01">
                </div>
                <div class="form-group">
                    <label class="form-label">সর্বনিম্ন অর্ডার (৳) <small style="color:var(--g400);">0=নেই</small></label>
                    <input type="number" class="form-control" name="min_order_amount" value="<?=$editing['min_order_amount']??0?>" min="0" step="0.01">
                </div>
                <div class="form-group">
                    <label class="form-label">ব্যবহার সীমা <small style="color:var(--g400);">0=সীমাহীন</small></label>
                    <input type="number" class="form-control" name="usage_limit" value="<?=$editing['usage_limit']??0?>" min="0">
                </div>
                <div class="form-group">
                    <label class="form-label">মেয়াদ শেষের তারিখ</label>
                    <input type="date" class="form-control" name="expiry_date" value="<?=$editing['expiry_date']??''?>">
                </div>

                <!-- Login & User restrictions -->
                <div style="background:var(--g100);border-radius:var(--r);padding:14px;margin-bottom:14px;">
                    <div style="font-weight:700;font-size:.88rem;color:var(--navy);margin-bottom:10px;"><i class="fas fa-user-lock"></i> অ্যাক্সেস নিয়ন্ত্রণ</div>
                    <div class="form-group" style="margin-bottom:10px;">
                        <label class="form-check">
                            <input type="checkbox" name="require_login" value="1" <?=($editing['require_login']??0)?'checked':''?>>
                            <span>লগইন ছাড়া ব্যবহার করা যাবে না</span>
                        </label>
                        <div class="form-hint">চেক করলে গেস্ট চেকআউটে এই কুপন কাজ করবে না।</div>
                    </div>
                    <div class="form-group" style="margin-bottom:0;">
                        <label class="form-label">নির্দিষ্ট গ্রাহকের জন্য <small style="color:var(--g400);">(ঐচ্ছিক)</small></label>
                        <select class="form-control" name="assigned_user_id">
                            <option value="">-- সবার জন্য --</option>
                            <?php foreach($users as $u):?>
                                <option value="<?=$u['id']?>" <?=($editing['assigned_user_id']??0)==$u['id']?'selected':''?>><?=e($u['name'])?> (<?=e($u['phone'])?>)</option>
                            <?php endforeach;?>
                        </select>
                        <div class="form-hint">নির্দিষ্ট গ্রাহক বাছাই করলে শুধু সেই অ্যাকাউন্ট থেকে কাজ করবে।</div>
                    </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 toggleMax(){document.getElementById('maxG').style.display=document.getElementById('discType').value==='percent'?'':'none';}</script>
<?php include __DIR__.'/includes/admin_footer.php';?>
