<?php
/**
 * سودانا — Notifications v2 (Complete)
 * Features: filter by type, mark-single-read, empty state, pagination
 * Route: /app/notifications.php
 */
require_once __DIR__ . '/../config.php';
session_start();
$u      = current_user();
$userId = $u ? (int)$u['id'] : 0;
if (!$userId) { header('Location: ' . url('?login=1')); exit; }
if (!$userId) { header('Location: ' . SITE_URL . '/'); exit; }
$lang  = $_SESSION['lang'] ?? 'ar';
$dir   = $lang === 'ar' ? 'rtl' : 'ltr';
$filter = $_GET['type'] ?? 'all';
$page   = max(1, (int)($_GET['page'] ?? 1));
$limit  = 20;
$offset = ($page - 1) * $limit;

// Mark single as read
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_id'])) {
    try { db()->prepare("UPDATE notifications SET read_at=NOW() WHERE id=? AND user_id=?")->execute([(int)$_POST['mark_id'], $userId]); } catch(Throwable $e){}
    header('Location: '.$_SERVER['REQUEST_URI']); exit;
}

$notifs = []; $unreadCount = 0; $totalCount = 0;
try {
    $where = "user_id = $userId";
    $params = [];
    $validTypes = ['payment_confirmed','payment_rejected','invoice_expired','settlement_paid','risk_block','booking_confirmed','booking_completed'];
    if ($filter !== 'all' && in_array($filter, $validTypes)) {
        $where .= " AND type = '$filter'";
    }
    $st = db()->prepare("SELECT * FROM notifications WHERE $where ORDER BY created_at DESC LIMIT $limit OFFSET $offset");
    $st->execute($params);
    $notifs = $st->fetchAll(PDO::FETCH_ASSOC);

    $uc = db()->prepare("SELECT COUNT(*) FROM notifications WHERE user_id=? AND read_at IS NULL");
    $uc->execute([$userId]);
    $unreadCount = (int)$uc->fetchColumn();

    $tc = db()->prepare("SELECT COUNT(*) FROM notifications WHERE $where");
    $tc->execute();
    $totalCount = (int)$tc->fetchColumn();

    // Mark all visible as read when viewing all
    if ($filter === 'all') {
        db()->prepare("UPDATE notifications SET read_at=NOW() WHERE user_id=? AND read_at IS NULL")->execute([$userId]);
    }
} catch(Throwable $e) {}

$pageTitle = $lang==='ar'?'الإشعارات':'Notifications';
$backUrl   = SITE_URL . '/app/dashboard.php';
$backLabel = $lang==='ar'?'لوحة التحكم':'Dashboard';
include __DIR__ . '/_head.php';

$icons = [
    'payment_confirmed'  => ['icon'=>'✅','color'=>'#D1FAE5','text_color'=>'#065F46'],
    'payment_rejected'   => ['icon'=>'❌','color'=>'#FEE2E2','text_color'=>'#991B1B'],
    'invoice_expired'    => ['icon'=>'⏳','color'=>'#FEF3C7','text_color'=>'#92400E'],
    'settlement_paid'    => ['icon'=>'💰','color'=>'#E0F2FE','text_color'=>'#0369A1'],
    'risk_block'         => ['icon'=>'🛡️','color'=>'#F3F4F6','text_color'=>'#374151'],
    'booking_confirmed'  => ['icon'=>'📅','color'=>'#D1FAE5','text_color'=>'#065F46'],
    'booking_completed'  => ['icon'=>'🏆','color'=>'#EDE9FE','text_color'=>'#5B21B6'],
];
$filterLabels = [
    'all'               => ($lang==='ar'?'الكل':'All'),
    'payment_confirmed' => ($lang==='ar'?'دفع مؤكد':'Payment'),
    'invoice_expired'   => ($lang==='ar'?'منتهية':'Expired'),
    'booking_confirmed' => ($lang==='ar'?'حجوزات':'Bookings'),
    'risk_block'        => ($lang==='ar'?'تنبيهات':'Alerts'),
];
?>
<style>
.notif-filter{display:flex;gap:8px;overflow-x:auto;padding:16px 0 8px;scrollbar-width:none}
.notif-filter::-webkit-scrollbar{display:none}
.filter-chip{padding:6px 14px;border-radius:20px;border:1.5px solid var(--border);font-size:.78rem;font-weight:700;cursor:pointer;white-space:nowrap;text-decoration:none;color:var(--text2);background:#fff;transition:all .15s}
.filter-chip.active,.filter-chip:hover{background:var(--g1);color:#fff;border-color:var(--g1)}
.notif-item{display:flex;align-items:flex-start;gap:12px;padding:14px 16px;border-bottom:1px solid var(--sand2);transition:background .15s;cursor:default}
.notif-item:hover{background:var(--sand)}
.notif-item.unread{background:#FFFDF5}
.notif-icon{width:38px;height:38px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1rem;flex-shrink:0}
.notif-body{flex:1}
.notif-title{font-size:.88rem;font-weight:600;margin-bottom:2px}
.notif-body p{font-size:.8rem;color:var(--text2);line-height:1.5}
.notif-time{font-size:.7rem;color:var(--text3);margin-top:3px}
.unread-dot{width:8px;height:8px;border-radius:50%;background:var(--g3);flex-shrink:0;margin-top:6px}
.empty-notif{text-align:center;padding:60px 20px;color:var(--text3)}
.empty-notif .ei{font-size:2.5rem;margin-bottom:12px}
.pager{display:flex;gap:8px;justify-content:center;padding:16px 0}
.pager a{padding:6px 14px;border:1.5px solid var(--border);border-radius:8px;font-size:.8rem;font-weight:600;text-decoration:none;color:var(--text2)}
.pager a.active,.pager a:hover{background:var(--g1);color:#fff;border-color:var(--g1)}
@media(max-width:480px){.notif-item{padding:12px 12px}}
</style>

<div class="page-wrap" style="max-width:640px;padding:0 0 32px">

  <!-- Header -->
  <div style="padding:16px 16px 0;display:flex;align-items:center;justify-content:space-between">
    <h1 style="font-size:1.1rem;font-weight:900;color:var(--g1)">
      🔔 <?= $lang==='ar'?'الإشعارات':'Notifications' ?>
      <?php if($unreadCount > 0): ?>
      <span style="background:var(--amber);color:#fff;font-size:.7rem;padding:2px 8px;border-radius:10px;margin-<?= $lang==='ar'?'right':'left' ?>:6px"><?= $unreadCount ?></span>
      <?php endif; ?>
    </h1>
    <span style="font-size:.75rem;color:var(--text3)"><?= $totalCount ?> <?= $lang==='ar'?'إشعار':'notifications' ?></span>
  </div>

  <!-- Filters -->
  <div class="notif-filter" style="padding:12px 16px">
    <?php foreach($filterLabels as $val => $label): ?>
    <a href="?type=<?= $val ?>" class="filter-chip <?= $filter===$val?'active':'' ?>"><?= $label ?></a>
    <?php endforeach; ?>
  </div>

  <!-- Notifications -->
  <div class="card" style="padding:0;overflow:hidden">
    <?php if(empty($notifs)): ?>
    <div class="empty-notif">
      <div class="ei">🔔</div>
      <p><?= $lang==='ar'?'لا إشعارات في هذا القسم':'No notifications in this section' ?></p>
      <a href="<?= SITE_URL ?>/app/services.php" style="color:var(--g3);font-weight:700;font-size:.85rem;display:inline-block;margin-top:8px">
        🚀 <?= $lang==='ar'?'ابدأ تنفيذاً جديداً':'Start a new execution' ?>
      </a>
    </div>
    <?php else: ?>
    <?php foreach($notifs as $n):
      $ic     = $icons[$n['type']] ?? ['icon'=>'📣','color'=>'#F3F4F6','text_color'=>'#374151'];
      $isUnread = !$n['read_at'];
    ?>
    <div class="notif-item <?= $isUnread?'unread':'' ?>">
      <div class="notif-icon" style="background:<?= $ic['color'] ?>;color:<?= $ic['text_color'] ?>"><?= $ic['icon'] ?></div>
      <div class="notif-body">
        <p class="notif-title" style="<?= $isUnread?'font-weight:800':'' ?>"><?= htmlspecialchars($n['title'] ?? '') ?></p>
        <?php if($n['body']): ?>
        <p><?= htmlspecialchars(mb_substr($n['body'], 0, 120)) ?><?= mb_strlen($n['body']??'')>120?'...':'' ?></p>
        <?php endif; ?>
        <p class="notif-time"><?= $n['created_at'] ? date('d/m/Y H:i', strtotime($n['created_at'])) : '' ?></p>
      </div>
      <?php if($isUnread): ?>
      <form method="POST" style="margin:0">
        <input type="hidden" name="mark_id" value="<?= $n['id'] ?>">
        <button type="submit" style="background:none;border:none;cursor:pointer;font-size:.65rem;color:var(--g3)" title="<?= $lang==='ar'?'وضع علامة مقروء':'Mark as read' ?>">✓</button>
      </form>
      <?php endif; ?>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <!-- Pagination -->
  <?php if($totalCount > $limit): ?>
  <div class="pager">
    <?php for($p=1; $p<=ceil($totalCount/$limit); $p++): ?>
    <a href="?type=<?= $filter ?>&page=<?= $p ?>" class="<?= $p===$page?'active':'' ?>"><?= $p ?></a>
    <?php endfor; ?>
  </div>
  <?php endif; ?>

</div>
<?php include __DIR__ . '/_foot.php'; ?>

<nav style="position:fixed;bottom:0;left:0;right:0;background:#fff;border-top:1px solid #e2e8f0;display:flex;padding:8px 0 calc(8px + env(safe-area-inset-bottom,0px));z-index:100">
  <a href="/app/hub.php" style="flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:#64748b;font-size:.6rem;font-family:inherit;padding:4px 0"><span style="font-size:1.1rem">&#127968;</span><span>الهب</span></a>
  <a href="/app/pay.php" style="flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:#64748b;font-size:.6rem;font-family:inherit;padding:4px 0"><span style="font-size:1.1rem">&#128179;</span><span>Pay</span></a>
  <a href="/app/invest/index.php" style="flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:#64748b;font-size:.6rem;font-family:inherit;padding:4px 0"><span style="font-size:1.1rem">&#128185;</span><span>استثمار</span></a>
  <a href="/app/community.php" style="flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:#64748b;font-size:.6rem;font-family:inherit;padding:4px 0"><span style="font-size:1.1rem">&#127968;</span><span>مجتمع</span></a>
  <a href="/app/profile.php" style="flex:1;display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:#64748b;font-size:.6rem;font-family:inherit;padding:4px 0"><span style="font-size:1.1rem">&#128100;</span><span>حسابي</span></a>
</nav>