<?php
require_once 'includes/auth.php';
$db = getDB();
$csrf = generateCSRFToken();

// Quick action (AJAX)
if (isset($_POST['quick_action'])) {
    header('Content-Type: application/json');
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) { echo json_encode(['success'=>false,'message'=>'CSRF error']); exit; }
    $action = $_POST['action'] ?? '';
    $cid = intval($_POST['couple_id'] ?? 0);
    if ($action === 'approve') {
        $db->prepare("UPDATE couples SET status='approved' WHERE id=?")->execute([$cid]);
        echo json_encode(['success'=>true,'message'=>'অনুমোদিত হয়েছে!']);
    } elseif ($action === 'reject') {
        $db->prepare("UPDATE couples SET status='rejected' WHERE id=?")->execute([$cid]);
        echo json_encode(['success'=>true,'message'=>'বাতিল করা হয়েছে!']);
    } elseif ($action === 'delete') {
        $db->prepare("DELETE FROM couples WHERE id=?")->execute([$cid]);
        echo json_encode(['success'=>true,'message'=>'মুছে ফেলা হয়েছে!']);
    } elseif ($action === 'feature') {
        $db->prepare("UPDATE couples SET is_featured = NOT is_featured WHERE id=?")->execute([$cid]);
        echo json_encode(['success'=>true,'message'=>'ফিচার আপডেট হয়েছে!']);
    } else {
        echo json_encode(['success'=>false,'message'=>'অজানা অ্যাকশন']);
    }
    exit;
}

// Edit form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_couple']) && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $cid = intval($_POST['couple_id'] ?? 0);
    $fields = ['boy_name','girl_name','nickname','marriage_date','district','upazila','short_story','love_duration','facebook_link','press_video_link','funny_title','status_text','contact_number','status','is_featured'];
    $set = [];
    $params = [];
    foreach ($fields as $f) {
        if (isset($_POST[$f])) {
            $set[] = "$f = ?";
            $val = trim($_POST[$f]);
            if ($f === 'marriage_date' && !$val) $val = null;
            if ($f === 'is_featured') $val = intval($val);
            $params[] = $val;
        }
    }
    // Photo upload
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $photo = uploadFile($_FILES['photo'], 'couples');
        if ($photo) { $set[] = "photo = ?"; $params[] = $photo; }
    }
    if ($set) {
        $params[] = $cid;
        $db->prepare("UPDATE couples SET " . implode(',', $set) . " WHERE id=?")->execute($params);
    }
    header('Location: couples.php?msg=updated'); exit;
}

// Delete
if (isset($_GET['delete']) && isset($_GET['csrf'])) {
    if (verifyCSRFToken($_GET['csrf'])) {
        $db->prepare("DELETE FROM couples WHERE id=?")->execute([intval($_GET['delete'])]);
    }
    header('Location: couples.php?msg=deleted'); exit;
}

// Filters
$status = $_GET['status'] ?? '';
$search = trim($_GET['q'] ?? '');
$page = max(1, intval($_GET['page'] ?? 1));
$offset = ($page - 1) * 20;

$where = "1=1";
$params = [];
if ($status) { $where .= " AND status=?"; $params[] = $status; }
if ($search) { $where .= " AND (boy_name LIKE ? OR girl_name LIKE ?)"; $like = "%$search%"; $params[] = $like; $params[] = $like; }

$total = $db->prepare("SELECT COUNT(*) FROM couples WHERE $where");
$total->execute($params);
$total = $total->fetchColumn();
$totalPages = ceil($total / 20);

$stmt = $db->prepare("SELECT * FROM couples WHERE $where ORDER BY created_at DESC LIMIT 20 OFFSET $offset");
$stmt->execute($params);
$couples = $stmt->fetchAll();

// Edit mode
$editing = null;
if (isset($_GET['edit'])) {
    $es = $db->prepare("SELECT * FROM couples WHERE id=?");
    $es->execute([intval($_GET['edit'])]);
    $editing = $es->fetch();
}

$pendingCount = $db->query("SELECT COUNT(*) FROM couples WHERE status='pending'")->fetchColumn();
$currentAdmin = e($_SESSION['admin_name'] ?? 'Admin');
?>
<!DOCTYPE html>
<html lang="bn" data-theme="dark">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>কাপল ম্যানেজ — তজিয়া গ্রুপ</title>
  <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
  <link rel="stylesheet" href="<?= SITE_URL ?>/assets/css/style.css">
</head>
<body>
<div class="admin-wrap">
  <aside class="admin-sidebar">
    <div class="logo">💕 তজিয়া গ্রুপ</div>
    <nav>
      <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> ড্যাশবোর্ড</a>
      <a href="couples.php" class="active"><i class="fas fa-users"></i> সব কাপল</a>
      <a href="pending.php"><i class="fas fa-clock"></i> অপেক্ষমাণ <span class="badge badge-pending" style="margin-left:auto;"><?= $pendingCount ?></span></a>
      <a href="settings.php"><i class="fas fa-cog"></i> সেটিংস</a>
      <a href="<?= SITE_URL ?>" target="_blank"><i class="fas fa-external-link-alt"></i> সাইট দেখুন</a>
      <a href="logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
    </nav>
  </aside>

  <div class="admin-main">
    <div class="admin-topbar">
      <div><button class="admin-sidebar-toggle" id="adminSidebarToggle"><i class="fas fa-bars"></i></button> <span style="font-weight:600;">কাপল ম্যানেজমেন্ট</span></div>
      <div style="color:var(--text-muted);">মোট: <?= bnNum($total) ?></div>
    </div>

    <div class="admin-content">
      <?php if (isset($_GET['msg'])): ?>
      <div class="alert alert-success">✅ সফলভাবে <?= $_GET['msg'] === 'deleted' ? 'মুছে ফেলা' : 'আপডেট' ?> হয়েছে!</div>
      <?php endif; ?>

      <!-- Edit Modal -->
      <?php if ($editing): ?>
      <div class="glass" style="margin-bottom:24px;">
        <h3 style="margin-bottom:16px;"><i class="fas fa-edit"></i> কাপল সম্পাদনা — <?= e($editing['boy_name']) ?> ❤ <?= e($editing['girl_name']) ?></h3>
        <form method="POST" enctype="multipart/form-data">
          <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
          <input type="hidden" name="edit_couple" value="1">
          <input type="hidden" name="couple_id" value="<?= $editing['id'] ?>">
          <div class="form-row">
            <div class="form-group"><label>ছেলের নাম</label><input type="text" name="boy_name" class="form-control" value="<?= e($editing['boy_name']) ?>" required></div>
            <div class="form-group"><label>মেয়ের নাম</label><input type="text" name="girl_name" class="form-control" value="<?= e($editing['girl_name']) ?>" required></div>
          </div>
          <div class="form-row">
            <div class="form-group"><label>ডাকনাম</label><input type="text" name="nickname" class="form-control" value="<?= e($editing['nickname']) ?>"></div>
            <div class="form-group"><label>বিয়ের তারিখ</label><input type="date" name="marriage_date" class="form-control" value="<?= e($editing['marriage_date']) ?>"></div>
          </div>
          <div class="form-row">
            <div class="form-group"><label>জেলা</label><input type="text" name="district" class="form-control" value="<?= e($editing['district']) ?>"></div>
            <div class="form-group"><label>উপজেলা</label><input type="text" name="upazila" class="form-control" value="<?= e($editing['upazila']) ?>"></div>
          </div>
          <div class="form-group"><label>সংক্ষিপ্ত গল্প</label><textarea name="short_story" class="form-control"><?= e($editing['short_story']) ?></textarea></div>
          <div class="form-row">
            <div class="form-group"><label>ভালোবাসার সময়কাল</label><input type="text" name="love_duration" class="form-control" value="<?= e($editing['love_duration']) ?>"></div>
            <div class="form-group"><label>ফেসবুক লিংক</label><input type="url" name="facebook_link" class="form-control" value="<?= e($editing['facebook_link']) ?>"></div>
          </div>
          <div class="form-row">
            <div class="form-group"><label>মজার টাইটেল</label><input type="text" name="funny_title" class="form-control" value="<?= e($editing['funny_title']) ?>"></div>
            <div class="form-group"><label>স্ট্যাটাস টেক্সট</label><input type="text" name="status_text" class="form-control" value="<?= e($editing['status_text']) ?>"></div>
          </div>
          <div class="form-row">
            <div class="form-group"><label>প্রেস ভিডিও লিংক</label><input type="url" name="press_video_link" class="form-control" value="<?= e($editing['press_video_link']) ?>"></div>
            <div class="form-group"><label>যোগাযোগ নম্বর</label><input type="text" name="contact_number" class="form-control" value="<?= e($editing['contact_number']) ?>"></div>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label>স্ট্যাটাস</label>
              <select name="status" class="form-control">
                <option value="pending" <?= $editing['status']==='pending'?'selected':'' ?>>অপেক্ষমাণ</option>
                <option value="approved" <?= $editing['status']==='approved'?'selected':'' ?>>অনুমোদিত</option>
                <option value="rejected" <?= $editing['status']==='rejected'?'selected':'' ?>>বাতিল</option>
              </select>
            </div>
            <div class="form-group">
              <label>ফিচার্ড</label>
              <select name="is_featured" class="form-control">
                <option value="0" <?= !$editing['is_featured']?'selected':'' ?>>না</option>
                <option value="1" <?= $editing['is_featured']?'selected':'' ?>>হ্যাঁ</option>
              </select>
            </div>
          </div>
          <div class="form-group"><label>নতুন ছবি (ঐচ্ছিক)</label><input type="file" name="photo" class="form-control" accept="image/*"></div>
          <div style="display:flex;gap:8px;">
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> সংরক্ষণ</button>
            <a href="couples.php" class="btn btn-outline">বাতিল</a>
          </div>
        </form>
      </div>
      <?php endif; ?>

      <!-- Filters -->
      <div class="glass" style="margin-bottom:24px;">
        <form method="GET" style="display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end;">
          <div class="form-group" style="margin:0;flex:1;min-width:150px;">
            <input type="text" name="q" class="form-control" value="<?= e($search) ?>" placeholder="নাম দিয়ে খুঁজুন...">
          </div>
          <div class="form-group" style="margin:0;">
            <select name="status" class="form-control">
              <option value="">সব স্ট্যাটাস</option>
              <option value="pending" <?= $status==='pending'?'selected':'' ?>>অপেক্ষমাণ</option>
              <option value="approved" <?= $status==='approved'?'selected':'' ?>>অনুমোদিত</option>
              <option value="rejected" <?= $status==='rejected'?'selected':'' ?>>বাতিল</option>
            </select>
          </div>
          <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-filter"></i> ফিল্টার</button>
        </form>
      </div>

      <!-- Table -->
      <div class="glass">
        <div style="overflow-x:auto;">
          <table class="admin-table">
            <thead>
              <tr><th>ছবি</th><th>কাপল</th><th>জেলা</th><th>স্ট্যাটাস</th><th>ভিউ</th><th>তারিখ</th><th>অ্যাকশন</th></tr>
            </thead>
            <tbody>
              <?php foreach ($couples as $c): ?>
              <tr>
                <td>
                  <?php if ($c['photo']): ?><img src="<?= UPLOAD_URL . e($c['photo']) ?>" alt="">
                  <?php else: ?><div style="width:50px;height:50px;background:var(--gradient);border-radius:8px;display:flex;align-items:center;justify-content:center;">💑</div><?php endif; ?>
                </td>
                <td>
                  <strong><?= e($c['boy_name']) ?></strong> ❤ <strong><?= e($c['girl_name']) ?></strong>
                  <?php if ($c['is_featured']): ?><span class="badge" style="background:rgba(255,45,117,0.2);color:var(--pink);margin-left:4px;">⭐</span><?php endif; ?>
                </td>
                <td><?= e($c['district'] ?? '—') ?></td>
                <td><span class="badge badge-<?= $c['status'] ?>"><?= $c['status']==='approved'?'অনুমোদিত':($c['status']==='pending'?'অপেক্ষমাণ':'বাতিল') ?></span></td>
                <td><?= bnNum($c['views']) ?></td>
                <td style="color:var(--text-muted);font-size:.85rem;"><?= bnTimeAgo($c['created_at']) ?></td>
                <td style="white-space:nowrap;">
                  <?php if ($c['status'] !== 'approved'): ?>
                  <button class="btn btn-sm btn-success quick-action" data-action="approve" data-id="<?= $c['id'] ?>" data-csrf="<?= $csrf ?>" title="অনুমোদন"><i class="fas fa-check"></i></button>
                  <?php endif; ?>
                  <?php if ($c['status'] !== 'rejected'): ?>
                  <button class="btn btn-sm btn-warning quick-action" data-action="reject" data-id="<?= $c['id'] ?>" data-csrf="<?= $csrf ?>" title="বাতিল"><i class="fas fa-times"></i></button>
                  <?php endif; ?>
                  <a href="couples.php?edit=<?= $c['id'] ?>" class="btn btn-sm btn-outline" title="সম্পাদনা"><i class="fas fa-edit"></i></a>
                  <a href="couples.php?delete=<?= $c['id'] ?>&csrf=<?= $csrf ?>" class="btn btn-sm btn-danger" data-confirm="আপনি কি নিশ্চিত?" title="মুছুন"><i class="fas fa-trash"></i></a>
                  <button class="btn btn-sm btn-outline quick-action" data-action="feature" data-id="<?= $c['id'] ?>" data-csrf="<?= $csrf ?>" title="ফিচার টগল"><i class="fas fa-star"></i></button>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>

        <?php if ($totalPages > 1): ?>
        <div class="pagination" style="margin-top:20px;">
          <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <a href="?page=<?= $i ?>&status=<?= e($status) ?>&q=<?= e($search) ?>" class="<?= $i==$page?'active':'' ?>"><?= bnNum($i) ?></a>
          <?php endfor; ?>
        </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>
<div class="toast-container"></div>
<script src="<?= SITE_URL ?>/assets/js/admin.js"></script>
</body>
</html>
