<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/mj_deal_helpers.php';
$admin = require_admin();
verify_csrf();
mj_deal_ensure_schema(); mj_review_ensure_schema();
$adminTitle = 'Deals Manager';
$adminSubtitle = 'Display and enquiry-only deals. Customers contact sellers directly; no customer payment is collected by MJ Marketplace.';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['deal_id'] ?? 0);
    $action = (string)($_POST['action'] ?? '');
    $note = trim((string)($_POST['admin_note'] ?? ''));
    try {
        $deal = $id > 0 ? one('SELECT * FROM mj_deals WHERE id=? LIMIT 1', [$id]) : null;
        if (!$deal) { throw new RuntimeException('Deal not found.'); }
        if ($action === 'approve') {
            q('UPDATE mj_deals SET status="active", approved_by=?, approved_at=NOW(), reject_reason=NULL, admin_note=?, updated_at=NOW() WHERE id=?', [(int)$admin['id'], $note, $id]);
            admin_log('deal_approved','mj_deals',$id,['note'=>$note]);
            if (!empty($deal['user_id'])) { mj263_notify((int)$deal['user_id'], null, 'deal_approved', 'Deal approved', 'Your deal is now live: '.($deal['title'] ?? ''), 'my-deals.php', 'normal', true); }
            flash('success','Deal approved and visible on frontend.');
        } elseif ($action === 'reject') {
            $reason = trim((string)($_POST['reject_reason'] ?? ''));
            if ($reason === '') { throw new RuntimeException('Reject reason is required.'); }
            q('UPDATE mj_deals SET status="rejected", reject_reason=?, admin_note=?, updated_at=NOW() WHERE id=?', [$reason, $note, $id]);
            admin_log('deal_rejected','mj_deals',$id,['reason'=>$reason]);
            if (!empty($deal['user_id'])) { mj263_notify((int)$deal['user_id'], null, 'deal_rejected', 'Deal rejected', 'Reason: '.$reason, 'my-deals.php', 'high', true); }
            flash('success','Deal rejected with reason.');
        } elseif ($action === 'pause') {
            q('UPDATE mj_deals SET status="paused", admin_note=?, updated_at=NOW() WHERE id=?', [$note, $id]);
            admin_log('deal_paused','mj_deals',$id,[]);
            flash('success','Deal paused.');
        } elseif ($action === 'activate') {
            q('UPDATE mj_deals SET status="active", updated_at=NOW() WHERE id=?', [$id]);
            admin_log('deal_activated','mj_deals',$id,[]);
            flash('success','Deal activated.');
        } elseif ($action === 'hide') {
            q('UPDATE mj_deals SET status="hidden", admin_note=?, updated_at=NOW() WHERE id=?', [$note, $id]);
            admin_log('deal_hidden','mj_deals',$id,[]);
            flash('success','Deal hidden from frontend.');
        } elseif ($action === 'feature') {
            $days = max(1, min(365, (int)($_POST['days'] ?? 7)));
            q('UPDATE mj_deals SET is_featured=1, featured_until=DATE_ADD(NOW(), INTERVAL '.$days.' DAY), status=IF(status IN ("draft","pending","rejected"),"active",status), updated_at=NOW() WHERE id=?', [$id]);
            admin_log('deal_featured','mj_deals',$id,['days'=>$days]);
            flash('success','Deal marked featured for '.$days.' days.');
        } elseif ($action === 'sponsor') {
            $days = max(1, min(365, (int)($_POST['days'] ?? 7)));
            q('UPDATE mj_deals SET is_sponsored=1, sponsored_until=DATE_ADD(NOW(), INTERVAL '.$days.' DAY), status=IF(status IN ("draft","pending","rejected"),"active",status), updated_at=NOW() WHERE id=?', [$id]);
            admin_log('deal_sponsored','mj_deals',$id,['days'=>$days]);
            flash('success','Deal marked sponsored for '.$days.' days.');
        }
    } catch (Throwable $e) { flash('error',$e->getMessage()); }
    redirect('deals.php');
}

$summary = mj_deal_admin_summary();
$status = trim((string)($_GET['status'] ?? ''));
$qText = trim((string)($_GET['q'] ?? ''));
$countryId = (int)($_GET['country_id'] ?? 0);
$where = ['1=1']; $params=[];
if ($status !== '') { $where[] = 'd.status=?'; $params[]=$status; }
if ($qText !== '') { $where[] = '(d.title LIKE ? OR d.description LIKE ? OR co.name LIKE ?)'; $like='%'.$qText.'%'; array_push($params,$like,$like,$like); }
if ($countryId > 0) { $where[] = 'd.country_id=?'; $params[]=$countryId; }
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 25; $offset = ($page-1)*$perPage;
$total = safe_count('SELECT COUNT(*) c FROM mj_deals d LEFT JOIN mj_companies co ON co.id=d.company_id WHERE '.implode(' AND ',$where), $params);
$deals = [];
try {
    $deals = all_rows("SELECT d.*, co.name AS company_name, c.name AS country_name, ci.name AS city_name, cat.name AS category_name, (SELECT COUNT(*) FROM mj_deal_revisions dr WHERE dr.deal_id=d.id AND dr.status='pending') pending_update_count FROM mj_deals d LEFT JOIN mj_companies co ON co.id=d.company_id LEFT JOIN mj_countries c ON c.id=d.country_id LEFT JOIN mj_cities ci ON ci.id=d.city_id LEFT JOIN mj_categories cat ON cat.id=d.category_id WHERE ".implode(' AND ',$where).' ORDER BY d.id DESC LIMIT '.$perPage.' OFFSET '.$offset, $params);
} catch (Throwable $e) { $deals=[]; }
$countries = table_exists('mj_countries') ? all_rows('SELECT id,name FROM mj_countries WHERE is_active=1 ORDER BY sort_order,name LIMIT 300') : [];
include __DIR__ . '/_header.php';
?>
<div class="alert alert-info border-0 shadow-sm">
  <i class="fas fa-shield-alt mr-1"></i><b>Payment scope locked:</b> Deals are display and enquiry only. Customers cannot checkout, buy vouchers, upload payment proof, or pay sellers through this website.
</div>
<div class="row">
  <div class="col-lg-2 col-6"><div class="small-box bg-info"><div class="inner"><h3><?= e($summary['total']) ?></h3><p>Total Deals</p></div><div class="icon"><i class="fas fa-fire"></i></div></div></div>
  <div class="col-lg-2 col-6"><div class="small-box bg-warning"><div class="inner"><h3><?= e($summary['pending']) ?></h3><p>Pending</p></div><div class="icon"><i class="fas fa-clock"></i></div></div></div>
  <div class="col-lg-2 col-6"><div class="small-box bg-success"><div class="inner"><h3><?= e($summary['active']) ?></h3><p>Active</p></div><div class="icon"><i class="fas fa-check-circle"></i></div></div></div>
  <div class="col-lg-2 col-6"><div class="small-box bg-secondary"><div class="inner"><h3><?= e($summary['expired']) ?></h3><p>Expired</p></div><div class="icon"><i class="fas fa-hourglass-end"></i></div></div></div>
  <div class="col-lg-2 col-6"><div class="small-box bg-primary"><div class="inner"><h3><?= e($summary['enquiries']) ?></h3><p>Enquiries</p></div><div class="icon"><i class="fas fa-envelope-open-text"></i></div></div></div>
  <div class="col-lg-2 col-6"><div class="small-box bg-danger"><div class="inner"><h3><?= e($summary['new_enquiries']) ?></h3><p>New Leads</p></div><div class="icon"><i class="fas fa-bell"></i></div></div></div>
</div>
<div class="card card-primary card-outline">
  <div class="card-header d-flex align-items-center"><h3 class="card-title"><i class="fas fa-fire mr-2"></i>All Deals</h3><div class="ml-auto"><a href="deal-create.php" class="btn btn-primary btn-sm"><i class="fas fa-plus mr-1"></i>Add Deal</a> <a href="deal-import.php" class="btn btn-outline-primary btn-sm"><i class="fas fa-file-import mr-1"></i>Import Deals</a> <a href="deal-revisions.php" class="btn btn-warning btn-sm"><i class="fas fa-code-branch mr-1"></i>Pending Updates</a> <a href="deal-enquiries.php" class="btn btn-outline-info btn-sm"><i class="fas fa-envelope mr-1"></i>Enquiries</a> <a href="report-deals.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-chart-line mr-1"></i>Report</a></div></div>
  <div class="card-body">
    <form class="row mb-3" method="get">
      <div class="col-md-4 mb-2"><input class="form-control" name="q" value="<?= e($qText) ?>" placeholder="Search deal title, company, description"></div>
      <div class="col-md-2 mb-2"><select class="form-control" name="status"><option value="">All statuses</option><?php foreach(['draft','pending','active','paused','expired','rejected','hidden'] as $s): ?><option value="<?= e($s) ?>" <?= $status===$s?'selected':'' ?>><?= e(ucwords($s)) ?></option><?php endforeach; ?></select></div>
      <div class="col-md-3 mb-2"><select class="form-control" name="country_id"><option value="0">All countries</option><?php foreach($countries as $c): ?><option value="<?= (int)$c['id'] ?>" <?= $countryId===(int)$c['id']?'selected':'' ?>><?= e($c['name']) ?></option><?php endforeach; ?></select></div>
      <div class="col-md-3 mb-2"><button class="btn btn-primary"><i class="fas fa-search mr-1"></i>Filter</button> <a class="btn btn-light" href="deals.php">Reset</a></div>
    </form>
    <div class="table-responsive">
      <table class="table table-hover table-striped">
        <thead><tr><th>Deal</th><th>Company</th><th>Location</th><th>Status</th><th>Performance</th><th>Expiry</th><th width="210">Action</th></tr></thead>
        <tbody>
        <?php if(!$deals): ?><tr><td colspan="7"><div class="mj-empty text-center py-4"><i class="fas fa-inbox fa-2x text-muted mb-2"></i><h5>No deals found</h5><p class="text-muted mb-0">Create a display deal to start collecting leads.</p></div></td></tr><?php endif; ?>
        <?php foreach($deals as $d): ?>
          <tr>
            <td><div class="d-flex align-items-center"><div class="mr-2" style="width:54px;height:54px;border-radius:12px;background:#f1f5f9;overflow:hidden"><?php if(!empty($d['image_path'])): ?><img src="../<?= e($d['image_path']) ?>" style="width:100%;height:100%;object-fit:cover"><?php else: ?><div class="text-center text-muted pt-3"><i class="fas fa-image"></i></div><?php endif; ?></div><div><b><?= e($d['title']) ?></b><br><small class="text-muted">Score <?= (int)($d['quality_score'] ?? 0) ?>% · <?= e($d['category_name'] ?? 'No category') ?></small><?php if((int)($d['pending_update_count']??0)>0): ?><br><a class="badge badge-warning" href="deal-revisions.php">Pending update review</a><?php endif; ?></div></div></td>
            <td><?= e($d['company_name'] ?? 'Direct Seller') ?></td>
            <td><?= e(trim(($d['city_name'] ?? '').' '.($d['country_name'] ?? ''))) ?></td>
            <td><?= mj_deal_status_badge((string)$d['status']) ?><?php if(!empty($d['is_featured'])): ?><br><span class="badge badge-primary mt-1">Featured</span><?php endif; ?><?php if(!empty($d['is_sponsored'])): ?><br><span class="badge badge-success mt-1">Sponsored</span><?php endif; ?></td>
            <td><small>Views: <?= (int)($d['view_count'] ?? 0) ?><br>Enquiries: <?= (int)($d['enquiry_count'] ?? 0) ?><br>WA/Call: <?= (int)($d['whatsapp_click_count'] ?? 0) ?>/<?= (int)($d['call_click_count'] ?? 0) ?></small></td>
            <td><small><?= e($d['end_at'] ? date('d M Y', strtotime($d['end_at'])) : 'No expiry') ?></small></td>
            <td>
              <div class="btn-group btn-group-sm mb-1"><a class="btn btn-outline-primary" href="deal-create.php?edit=<?= (int)$d['id'] ?>">Edit</a><a class="btn btn-outline-info" target="_blank" href="../deal.php?id=<?= (int)$d['id'] ?>">View</a><a class="btn btn-outline-secondary" href="deal-enquiries.php?deal_id=<?= (int)$d['id'] ?>">Leads</a></div>
              <form method="post" class="d-inline"><?= csrf_input() ?><input type="hidden" name="deal_id" value="<?= (int)$d['id'] ?>"><button name="action" value="approve" class="btn btn-xs btn-success" onclick="return confirm('Approve this deal?')">Approve</button> <button name="action" value="pause" class="btn btn-xs btn-warning">Pause</button> <button name="action" value="hide" class="btn btn-xs btn-secondary">Hide</button></form>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php $pages=max(1,(int)ceil($total/$perPage)); if($pages>1): ?><nav><ul class="pagination pagination-sm mb-0"><?php for($i=max(1,$page-2);$i<=min($pages,$page+2);$i++): ?><li class="page-item <?= $i===$page?'active':'' ?>"><a class="page-link" href="?<?= e(http_build_query(array_merge($_GET,['page'=>$i]))) ?>"><?= $i ?></a></li><?php endfor; ?></ul></nav><?php endif; ?>
  </div>
</div>
<?php include __DIR__ . '/_footer.php'; ?>
