<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

/* ===== DEBUG ===== */
$debug = (isset($_GET['debug']) && $_GET['debug'] === '1');
ini_set('display_errors', $debug ? '1' : '0');
ini_set('display_startup_errors', $debug ? '1' : '0');
error_reporting(E_ALL);

set_exception_handler(function (Throwable $e) use ($debug) {
    http_response_code(500);
    if (!$debug) {
        echo 'HTTP ERROR 500';
        exit;
    }

    echo "<pre style='direction:ltr;text-align:left;background:#111;color:#fff;padding:14px;border-radius:10px;white-space:pre-wrap'>";
    echo "UNCAUGHT EXCEPTION\n";
    echo "Message: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . "\n";
    echo "Line: " . $e->getLine() . "\n\n";
    echo $e->getTraceAsString();
    echo "</pre>";
    exit;
});

/* ===== Includes ===== */
require_once __DIR__ . '/inc/auth.php';
require_once __DIR__ . '/inc/layout.php';

require_login();

if (!is_owner()) {
    http_response_code(403);
    exit('غير مصرح');
}

/* ===== DB ===== */
$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

/* ===== Helpers ===== */
function table_exists_local(PDO $pdo, string $table): bool
{
    $st = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
          AND table_name = ?
    ");
    $st->execute([$table]);
    return (int)$st->fetchColumn() > 0;
}

function get_employee_name_expr(PDO $pdo): string
{
    $cols = [];
    try {
        $st = $pdo->query("SHOW COLUMNS FROM `employees`");
        $cols = $st->fetchAll(PDO::FETCH_COLUMN, 0);
    } catch (Throwable $e) {
        $cols = [];
    }

    foreach (['full_name', 'name', 'employee_name', 'emp_name', 'first_name'] as $c) {
        if (in_array($c, $cols, true)) {
            return "COALESCE(NULLIF(e.`$c`,''), CONCAT('موظف #', e.id))";
        }
    }

    return "CONCAT('موظف #', e.id)";
}

function popup_target_label(array $row): string
{
    $type = (string)($row['target_type'] ?? '');

    if ($type === 'all_branches') {
        return 'كل الفروع';
    }

    if ($type === 'single_branch') {
        return 'فرع: ' . branch_name_ar((int)($row['target_branch_id'] ?? 0));
    }

    if ($type === 'employee') {
        $empName = trim((string)($row['target_employee_name'] ?? ''));
        if ($empName !== '') {
            return 'موظف محدد: ' . $empName;
        }
        return 'موظف محدد #' . (int)($row['target_employee_id'] ?? 0);
    }

    return 'غير محدد';
}

/* ===== Check tables ===== */
if (!table_exists_local($pdo, 'owner_popup_messages')) {
    http_response_code(500);
    exit('جدول owner_popup_messages غير موجود');
}
if (!table_exists_local($pdo, 'owner_popup_message_reads')) {
    http_response_code(500);
    exit('جدول owner_popup_message_reads غير موجود');
}
if (!table_exists_local($pdo, 'employees')) {
    http_response_code(500);
    exit('جدول employees غير موجود');
}

/* ===== Filters ===== */
$statusFilter = strtolower(trim((string)($_GET['status'] ?? 'all')));
if (!in_array($statusFilter, ['all', 'active', 'inactive'], true)) {
    $statusFilter = 'all';
}

$q = trim((string)($_GET['q'] ?? ''));
$messageId = (int)($_GET['message_id'] ?? 0);

/* ===== Discover employee name expr ===== */
$empNameExpr = get_employee_name_expr($pdo);

/* ===== Messages list ===== */
$where = [];
$params = [];

if ($statusFilter === 'active') {
    $where[] = "m.is_active = 1";
} elseif ($statusFilter === 'inactive') {
    $where[] = "m.is_active = 0";
}

if ($q !== '') {
    $where[] = "(m.title LIKE :q OR m.message LIKE :q)";
    $params[':q'] = '%' . $q . '%';
}

if ($messageId > 0) {
    $where[] = "m.id = :mid";
    $params[':mid'] = $messageId;
}

$sqlMessages = "
    SELECT
        m.*,
        (
            SELECT COUNT(*)
            FROM owner_popup_message_reads rr
            WHERE rr.message_id = m.id
        ) AS reads_count,
        te.id AS target_employee_join_id,
        {$empNameExpr} AS target_employee_name
    FROM owner_popup_messages m
    LEFT JOIN employees e ON e.id = m.target_employee_id
    LEFT JOIN employees te ON te.id = m.target_employee_id
";

if ($where) {
    $sqlMessages .= " WHERE " . implode(' AND ', $where);
}

$sqlMessages .= " ORDER BY m.id DESC";

$st = $pdo->prepare($sqlMessages);
$st->execute($params);
$messages = $st->fetchAll();

/* ===== Selected message ===== */
$selectedMessage = null;
if ($messageId > 0) {
    foreach ($messages as $m) {
        if ((int)$m['id'] === $messageId) {
            $selectedMessage = $m;
            break;
        }
    }
} elseif (!empty($messages)) {
    $selectedMessage = $messages[0];
    $messageId = (int)$selectedMessage['id'];
}

/* ===== Readers ===== */
$readers = [];
if ($messageId > 0) {
 $sqlReaders = "
SELECT
    r.id,
    r.message_id,
    r.employee_id,
    r.seen_at,

    COALESCE(
        NULLIF(e.full_name,''),
        NULLIF(u.name,''),
        NULLIF(u.username,''),
        CONCAT('موظف #', r.employee_id)
    ) AS employee_name,

    COALESCE(e.branch_id, u.branch_id) AS branch_id,

    CASE 
        WHEN COALESCE(e.branch_id, u.branch_id) = 1 THEN 'أبوظبي'
        WHEN COALESCE(e.branch_id, u.branch_id) = 2 THEN 'دبي'
        WHEN COALESCE(e.branch_id, u.branch_id) = 3 THEN 'الشارقة'
        WHEN COALESCE(e.branch_id, u.branch_id) = 4 THEN 'العين'
        ELSE 'غير محدد'
    END AS branch_name

FROM owner_popup_message_reads r

LEFT JOIN users u
ON u.id = r.employee_id

LEFT JOIN employees e
ON e.user_id = u.id

WHERE r.message_id = ?

ORDER BY r.seen_at DESC
";
    $st = $pdo->prepare($sqlReaders);
    $st->execute([$messageId]);
    $readers = $st->fetchAll();
}

render_layout_start('إحصائيات الرسائل المنبثقة');
?>

<style>
  :root{
    --bg-main:#07171d;
    --bg-card:rgba(255,255,255,.05);
    --bg-card-2:rgba(255,255,255,.04);
    --line:rgba(255,255,255,.08);
    --text:#ffffff;
    --muted:rgba(255,255,255,.68);
    --gold:#d4af37;
    --gold-2:#ffd76a;
    --success:#34d399;
    --danger:#f87171;
    --shadow:0 18px 40px rgba(0,0,0,.16);
  }

  body{
    background:
      radial-gradient(circle at 20% 20%, rgba(10,77,87,.85), transparent 40%),
      radial-gradient(circle at 80% 80%, rgba(13,106,122,.55), transparent 40%),
      #021d23;
  }

  .popup-stats-page{
    color:var(--text);
    width:100%;
    max-width:100%;
  }

  .popup-stats-page *{
    box-sizing:border-box;
  }

  .popup-stats-page .topbar-local{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:10px 12px;
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    position:sticky;
    top:12px;
    z-index:10;
    margin-bottom:18px;
    backdrop-filter:blur(12px);
    flex-wrap:wrap;
  }

  .popup-stats-page .owner-badge{
    display:inline-flex;
    align-items:center;
    gap:8px;
    background:rgba(255,255,255,.05);
    border:1px solid var(--line);
    border-radius:999px;
    padding:10px 12px;
    font-weight:900;
    color:#fff;
    box-shadow:0 8px 18px rgba(0,0,0,.10);
    backdrop-filter:blur(8px);
  }

  .popup-stats-page .owner-dot{
    width:8px;
    height:8px;
    border-radius:50%;
    background:var(--gold);
    box-shadow:0 0 0 4px rgba(212,175,55,.14);
  }

  .popup-stats-page .btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    height:40px;
    padding:0 14px;
    border-radius:999px;
    border:1px solid rgba(212,175,55,.25);
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    color:#1d1600;
    font-weight:900;
    cursor:pointer;
    text-decoration:none;
    font-family:inherit;
    box-shadow:0 12px 24px rgba(212,175,55,.18);
    transition:.18s ease;
  }

  .popup-stats-page .btn:hover{
    transform:translateY(-2px);
    box-shadow:0 16px 28px rgba(212,175,55,.24);
  }

  .popup-stats-page .btn.secondary{
    background:rgba(255,255,255,.05);
    color:#fff;
    border:1px solid var(--line);
    box-shadow:none;
  }

  .popup-stats-page .page-head{
    margin:18px 6px 14px;
  }

  .popup-stats-page .pageTitle{
    margin:0;
    font-size:30px;
    font-weight:900;
    color:#ffffff;
    line-height:1.1;
  }

  .popup-stats-page .pageSub{
    margin-top:6px;
    color:rgba(255,255,255,.72);
    font-size:14px;
    line-height:1.8;
  }

  .popup-stats-page .grid{
    display:grid;
    grid-template-columns:380px minmax(0,1fr);
    gap:18px;
    align-items:start;
  }

  @media(max-width:1100px){
    .popup-stats-page .grid{
      grid-template-columns:1fr;
    }
  }

  .popup-stats-page .card{
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    padding:16px;
    backdrop-filter:blur(12px);
  }

  .popup-stats-page .filters{
    display:grid;
    grid-template-columns:1fr 160px auto;
    gap:10px;
    margin-bottom:14px;
  }

  @media(max-width:700px){
    .popup-stats-page .filters{
      grid-template-columns:1fr;
    }
  }

  .popup-stats-page label{
    display:block;
    margin:0 0 6px;
    color:#ffffff;
    font-size:14px;
    font-weight:700;
  }

  .popup-stats-page .input,
  .popup-stats-page select{
    width:100%;
    box-sizing:border-box;
    padding:12px 12px;
    border-radius:12px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    color:#fff;
    outline:none;
    font-family:inherit;
  }

  .popup-stats-page select option{
    background:#0b1f26;
    color:#fff;
  }

  .popup-stats-page .input:focus,
  .popup-stats-page select:focus{
    border-color:rgba(212,175,55,.45);
    box-shadow:0 0 0 3px rgba(212,175,55,.12);
    background:rgba(255,255,255,.06);
  }

  .popup-stats-page .message-list{
    display:flex;
    flex-direction:column;
    gap:10px;
    max-height:70vh;
    overflow:auto;
    padding-right:4px;
  }

  .popup-stats-page .message-item{
    display:block;
    text-decoration:none;
    color:#fff;
    border:1px solid var(--line);
    background:rgba(255,255,255,.04);
    border-radius:16px;
    padding:14px;
    transition:.18s ease;
  }

  .popup-stats-page .message-item:hover{
    transform:translateY(-2px);
    background:rgba(255,255,255,.06);
  }

  .popup-stats-page .message-item.active{
    border-color:rgba(212,175,55,.40);
    box-shadow:0 0 0 4px rgba(212,175,55,.08);
    background:rgba(212,175,55,.08);
  }

  .popup-stats-page .message-title{
    font-size:18px;
    font-weight:900;
    margin:0 0 8px;
  }

  .popup-stats-page .message-snippet{
    color:var(--muted);
    font-size:13px;
    line-height:1.8;
    max-height:48px;
    overflow:hidden;
  }

  .popup-stats-page .meta{
    display:flex;
    flex-wrap:wrap;
    gap:8px;
    margin-top:10px;
  }

  .popup-stats-page .pill{
    font-size:12px;
    padding:5px 9px;
    border-radius:999px;
    background:rgba(255,255,255,.05);
    color:#fff;
    border:1px solid var(--line);
  }

  .popup-stats-page .pill.gold{
    color:#ffd76a;
    border-color:rgba(212,175,55,.26);
    background:rgba(212,175,55,.10);
  }

  .popup-stats-page .pill.green{
    color:#bbf7d0;
    border-color:rgba(52,211,153,.26);
    background:rgba(52,211,153,.10);
  }

  .popup-stats-page .pill.red{
    color:#fecaca;
    border-color:rgba(248,113,113,.26);
    background:rgba(248,113,113,.10);
  }

  .popup-stats-page .detail-head{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    gap:14px;
    flex-wrap:wrap;
    margin-bottom:14px;
  }

  .popup-stats-page .detail-title{
    margin:0;
    font-size:26px;
    font-weight:900;
  }

  .popup-stats-page .detail-body{
    background:rgba(255,255,255,.03);
    border:1px solid var(--line);
    border-radius:16px;
    padding:16px;
    line-height:2;
    color:rgba(255,255,255,.90);
    white-space:pre-wrap;
    margin-bottom:14px;
  }

  .popup-stats-page .stats-row{
    display:grid;
    grid-template-columns:repeat(4, minmax(0,1fr));
    gap:12px;
    margin-bottom:16px;
  }

  @media(max-width:900px){
    .popup-stats-page .stats-row{
      grid-template-columns:repeat(2, minmax(0,1fr));
    }
  }

  @media(max-width:560px){
    .popup-stats-page .stats-row{
      grid-template-columns:1fr;
    }
  }

  .popup-stats-page .stat{
    border-radius:16px;
    padding:14px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.04);
  }

  .popup-stats-page .stat .num{
    font-size:28px;
    font-weight:900;
    color:#ffd76a;
    line-height:1;
    margin-bottom:6px;
  }

  .popup-stats-page .stat .lab{
    color:var(--muted);
    font-size:13px;
  }

  .popup-stats-page table{
    width:100%;
    border-collapse:collapse;
    overflow:hidden;
    border-radius:16px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.03);
  }

  .popup-stats-page th,
  .popup-stats-page td{
    padding:12px 10px;
    border-bottom:1px solid rgba(255,255,255,.06);
    text-align:right;
    vertical-align:top;
  }

  .popup-stats-page th{
    background:rgba(255,255,255,.05);
    color:#ffd76a;
    font-size:13px;
  }

  .popup-stats-page tr:hover td{
    background:rgba(255,255,255,.03);
  }

  .popup-stats-page .empty{
    padding:22px;
    border:1px dashed rgba(255,255,255,.14);
    border-radius:16px;
    color:var(--muted);
    text-align:center;
    background:rgba(255,255,255,.03);
  }
</style>

<div class="popup-stats-page">
  <div class="topbar-local">
    <div class="owner-badge">
      <span class="owner-dot"></span>
      <span>OWNER ONLY</span>
    </div>

    <div style="display:flex;gap:10px;flex-wrap:wrap;">
      <a class="btn secondary" href="<?= h(u('dashboard.php')) ?>">العودة للوحة التحكم</a>
      <a class="btn" href="<?= h(u('hr_comms.php')) ?>">إرسال رسالة جديدة</a>
    </div>
  </div>

  <div class="page-head">
    <h1 class="pageTitle">إحصائيات الرسائل المنبثقة</h1>
    <div class="pageSub">عرض الرسائل المرسلة ومعرفة من شاهد كل رسالة ووقت القراءة.</div>
  </div>

  <div class="card" style="margin-bottom:18px;">
    <form method="get" class="filters">
      <div>
        <label>بحث</label>
        <input class="input" type="text" name="q" value="<?= h($q) ?>" placeholder="عنوان الرسالة أو جزء من النص">
      </div>

      <div>
        <label>الحالة</label>
        <select name="status">
          <option value="all" <?= $statusFilter === 'all' ? 'selected' : '' ?>>الكل</option>
          <option value="active" <?= $statusFilter === 'active' ? 'selected' : '' ?>>نشطة</option>
          <option value="inactive" <?= $statusFilter === 'inactive' ? 'selected' : '' ?>>غير نشطة</option>
        </select>
      </div>

      <div style="display:flex;align-items:flex-end;">
        <button class="btn" type="submit">تصفية</button>
      </div>
    </form>
  </div>

  <div class="grid">
    <div class="card">
      <div style="font-size:18px;font-weight:900;margin-bottom:12px;">قائمة الرسائل</div>

      <?php if (empty($messages)): ?>
        <div class="empty">لا توجد رسائل منبثقة مطابقة.</div>
      <?php else: ?>
        <div class="message-list">
          <?php foreach ($messages as $m): ?>
            <?php
              $isActive = ((int)$m['id'] === (int)$messageId);
              $url = u('owner_popup_stats.php?message_id=' . (int)$m['id']
                    . '&status=' . urlencode($statusFilter)
                    . '&q=' . urlencode($q));
            ?>
            <a class="message-item <?= $isActive ? 'active' : '' ?>" href="<?= h($url) ?>">
              <div class="message-title"><?= h((string)$m['title']) ?></div>
              <div class="message-snippet"><?= h((string)$m['message']) ?></div>

              <div class="meta">
                <span class="pill gold"><?= h(popup_target_label($m)) ?></span>
                <span class="pill <?= ((int)$m['is_active'] === 1) ? 'green' : 'red' ?>">
                  <?= ((int)$m['is_active'] === 1) ? 'نشطة' : 'متوقفة' ?>
                </span>
                <span class="pill">عدد القراءات: <?= (int)($m['reads_count'] ?? 0) ?></span>
                <span class="pill"><?= h((string)$m['created_at']) ?></span>
              </div>
            </a>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>

    <div class="card">
      <?php if (!$selectedMessage): ?>
        <div class="empty">اختر رسالة من القائمة لعرض التفاصيل.</div>
      <?php else: ?>
        <?php
          $readsCount = count($readers);
        ?>
        <div class="detail-head">
          <div>
            <h2 class="detail-title"><?= h((string)$selectedMessage['title']) ?></h2>
            <div class="meta" style="margin-top:10px;">
              <span class="pill gold"><?= h(popup_target_label($selectedMessage)) ?></span>
              <span class="pill <?= ((int)$selectedMessage['is_active'] === 1) ? 'green' : 'red' ?>">
                <?= ((int)$selectedMessage['is_active'] === 1) ? 'نشطة' : 'متوقفة' ?>
              </span>
              <span class="pill">تاريخ الإنشاء: <?= h((string)$selectedMessage['created_at']) ?></span>
            </div>
          </div>
        </div>

        <div class="detail-body"><?= h((string)$selectedMessage['message']) ?></div>

        <div class="stats-row">
          <div class="stat">
            <div class="num"><?= (int)$selectedMessage['id'] ?></div>
            <div class="lab">رقم الرسالة</div>
          </div>
          <div class="stat">
            <div class="num"><?= $readsCount ?></div>
            <div class="lab">عدد من شاهدوا الرسالة</div>
          </div>
          <div class="stat">
            <div class="num"><?= ((int)$selectedMessage['is_active'] === 1) ? '1' : '0' ?></div>
            <div class="lab">حالة التفعيل</div>
          </div>
          <div class="stat">
            <div class="num"><?= h((string)$selectedMessage['target_type']) ?></div>
            <div class="lab">نوع الاستهداف</div>
          </div>
        </div>

        <div style="font-size:18px;font-weight:900;margin:4px 0 12px;">الموظفون الذين شاهدوا الرسالة</div>

        <?php if (empty($readers)): ?>
          <div class="empty">لا يوجد أي موظف شاهد هذه الرسالة حتى الآن.</div>
        <?php else: ?>
          <div style="overflow:auto;">
            <table>
              <thead>
                <tr>
                  <th>الموظف</th>
                  <th>رقم الموظف</th>
                  <th>الفرع</th>
                  <th>وقت القراءة</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($readers as $r): ?>
                  <tr>
                    <td><?= h((string)($r['employee_name'] ?? ('موظف #' . (int)$r['employee_id']))) ?></td>
                    <td><?= (int)$r['employee_id'] ?></td>
                    <td><?= h(branch_name_ar((int)($r['branch_id'] ?? 0))) ?></td>
                    <td><?= h((string)$r['seen_at']) ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      <?php endif; ?>
    </div>
  </div>
</div>

<?php render_layout_end(); ?>