<?php
require_once __DIR__ . '/auth.php';
$codes = $pdo->query("SELECT g.*,(SELECT COUNT(*) FROM giftcode_claims gc WHERE gc.giftcode_id=g.id) as used_count FROM giftcodes g ORDER BY g.id DESC")->fetchAll();
?><!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Gift Codes — PakClub Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#0b0e18;color:#e8eaf0;font-family:'Segoe UI',sans-serif;display:flex;min-height:100vh}
.main{flex:1;overflow-x:hidden}
.topbar{background:#111827;border-bottom:1px solid rgba(255,255,255,.07);padding:16px 28px;display:flex;align-items:center;justify-content:space-between}
.topbar h2{font-size:20px;font-weight:700;color:#fff}
.content{padding:24px 28px;display:grid;grid-template-columns:360px 1fr;gap:20px}
.create-panel{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;padding:24px;align-self:start}
.create-panel h3{font-size:16px;font-weight:700;color:#fff;margin-bottom:20px;display:flex;align-items:center;gap:8px}
.field{margin-bottom:16px}
.field label{display:block;font-size:12px;color:#6b7280;text-transform:uppercase;letter-spacing:.6px;margin-bottom:8px;font-weight:600}
input[type=text],input[type=number]{width:100%;background:#0f1117;border:1px solid rgba(255,255,255,.1);border-radius:8px;padding:11px 14px;color:#fff;font-size:14px;outline:none;transition:border-color .2s}
input:focus{border-color:#f26d0f}
.hint{font-size:11px;color:#6b7280;margin-top:5px}
.btn{padding:10px 18px;border-radius:10px;border:none;cursor:pointer;font-size:13px;font-weight:600;display:inline-flex;align-items:center;gap:7px;transition:opacity .2s}
.btn:hover{opacity:.85}
.btn-orange{background:#f26d0f;color:#fff;width:100%;justify-content:center;padding:13px}
.btn-sm{padding:6px 12px;font-size:12px;border-radius:7px}
.btn-red{background:#ef4444;color:#fff}
.btn-gray{background:#374151;color:#e5e7eb}
.card{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;overflow:hidden}
table{width:100%;border-collapse:collapse;font-size:13px}
th{padding:11px 16px;color:#4b5563;font-size:11px;text-transform:uppercase;letter-spacing:.7px;border-bottom:1px solid rgba(255,255,255,.06);text-align:left;font-weight:600}
td{padding:12px 16px;border-bottom:1px solid rgba(255,255,255,.04);color:#c9ccd6;vertical-align:middle}
tr:last-child td{border-bottom:none}
tr:hover td{background:rgba(255,255,255,.02)}
.code-text{font-family:monospace;font-size:15px;font-weight:700;color:#f26d0f;letter-spacing:1px}
.progress-bar{height:6px;background:rgba(255,255,255,.08);border-radius:3px;overflow:hidden;margin-top:6px;width:120px}
.progress-fill{height:100%;background:#f26d0f;border-radius:3px}
.pill{padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
.pill-on{background:rgba(34,197,94,.15);color:#22c55e}
.pill-off{background:rgba(239,68,68,.15);color:#ef4444}
.actions{display:flex;gap:6px}
.rng-btn{margin-top:0;background:rgba(242,109,15,.15);border:1px solid rgba(242,109,15,.3);color:#f26d0f;border-radius:6px;padding:5px 10px;font-size:11px;cursor:pointer;font-weight:600}
@media(max-width:900px){.content{grid-template-columns:1fr}}
</style>
</head><body>
<?php include 'sidebar.php'; ?>
<div class="main">
  <div class="topbar">
    <h2><i class="fa-solid fa-gift" style="color:#f26d0f;margin-right:10px"></i>Gift Codes</h2>
  </div>
  <div class="content">
    <div class="create-panel">
      <h3><i class="fa-solid fa-plus-circle" style="color:#f26d0f"></i> Create Gift Code</h3>
      <div class="field">
        <label>Code <button class="rng-btn" onclick="genCode()"><i class="fa-solid fa-dice"></i> Random</button></label>
        <input type="text" id="gcCode" placeholder="e.g. PAKBONUS50" maxlength="30" style="text-transform:uppercase" oninput="this.value=this.value.toUpperCase()">
        <div class="hint">Letters, numbers and hyphens only</div>
      </div>
      <div class="field">
        <label>Bonus Amount (Rs)</label>
        <input type="number" id="gcAmt" placeholder="e.g. 50" min="1" step="0.01">
      </div>
      <div class="field">
        <label>Max Claims</label>
        <input type="number" id="gcMax" value="100" min="1">
        <div class="hint">How many users can claim this code</div>
      </div>
      <button class="btn btn-orange" onclick="createCode()"><i class="fa-solid fa-plus"></i> Create Gift Code</button>
    </div>

    <div class="card">
      <table>
        <tr><th>Code</th><th>Amount</th><th>Claims</th><th>Usage</th><th>Created</th><th>Status</th><th>Actions</th></tr>
        <?php foreach($codes as $c): $pct=$c['max_claims']>0?min(100,round($c['used_count']/$c['max_claims']*100)):0; ?>
        <tr>
          <td><span class="code-text"><?= htmlspecialchars($c['code']) ?></span></td>
          <td style="color:#22c55e;font-weight:700">Rs<?= number_format($c['amount'],2) ?></td>
          <td><?= $c['used_count'] ?>/<?= $c['max_claims'] ?></td>
          <td>
            <div style="font-size:12px;color:#9ca3af"><?= $pct ?>%</div>
            <div class="progress-bar"><div class="progress-fill" style="width:<?= $pct ?>%"></div></div>
          </td>
          <td style="font-size:12px"><?= date('M d Y',strtotime($c['created_at'])) ?></td>
          <td><span class="pill pill-<?= $c['status']?'on':'off' ?>"><?= $c['status']?'Active':'Inactive' ?></span></td>
          <td>
            <div class="actions">
              <button class="btn btn-gray btn-sm" onclick="toggleCode(<?= $c['id'] ?>,this)"><?= $c['status']?'Disable':'Enable' ?></button>
              <button class="btn btn-red btn-sm" onclick="deleteCode(<?= $c['id'] ?>)"><i class="fa-solid fa-trash"></i></button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if(!$codes): ?><tr><td colspan="7" style="text-align:center;padding:30px;color:#4b5563">No gift codes yet</td></tr><?php endif; ?>
      </table>
    </div>
  </div>
</div>
<div id="toast" style="position:fixed;bottom:30px;left:50%;transform:translateX(-50%);background:rgba(20,20,20,.9);backdrop-filter:blur(10px);color:#fff;padding:12px 24px;border-radius:30px;font-size:13px;display:none;z-index:9999;white-space:nowrap"></div>
<script>
function toast(m,ok=true){const t=document.getElementById('toast');t.style.display='block';t.style.borderLeft='3px solid '+(ok?'#22c55e':'#ef4444');t.innerText=m;setTimeout(()=>t.style.display='none',2500);}
function api(data,cb){const fd=new FormData();for(const[k,v]of Object.entries(data))fd.append(k,v);fetch('actions.php',{method:'POST',body:fd}).then(r=>r.json()).then(cb).catch(()=>toast('Network error',false));}
function genCode(){const chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';let c='';for(let i=0;i<8;i++)c+=chars[Math.floor(Math.random()*chars.length)];document.getElementById('gcCode').value='PAK'+c;}
function createCode(){
  const code=document.getElementById('gcCode').value.trim();
  const amt=parseFloat(document.getElementById('gcAmt').value);
  const max=parseInt(document.getElementById('gcMax').value);
  if(!code||!amt||!max){toast('Fill all fields',false);return;}
  api({action:'create_giftcode',code,amount:amt,max_claims:max},r=>{toast(r.ok?'Gift code created!':r.msg,r.ok);if(r.ok)setTimeout(()=>location.reload(),1000);});
}
function toggleCode(id,btn){api({action:'toggle_giftcode',id},r=>{if(r.ok){toast('Updated');btn.textContent=r.status?'Disable':'Enable';const row=btn.closest('tr');const pill=row.querySelector('.pill');pill.textContent=r.status?'Active':'Inactive';pill.className='pill pill-'+(r.status?'on':'off');}else toast(r.msg,false);});}
function deleteCode(id){if(!confirm('Delete this gift code? All claim history will be lost.'))return;api({action:'delete_giftcode',id},r=>{toast(r.ok?'Deleted':r.msg,r.ok);if(r.ok)setTimeout(()=>location.reload(),800);});}
</script>
</body></html>
