<?php
// ============================================================
// ajax/pending_counts.php
// Polled by the bell icon in includes/header.php every 30s.
//
// This replaces the old hardcoded bell dropdown (3 fake rows,
// hand-typed straight into header.php) with the real pending
// leave / permission / late-mark counts for the logged-in user,
// scoped to their own reportees via reporting_manager_id — the
// same way the mobile API already scopes its pending_* actions.
// ============================================================
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/functions.php';
startSession();
header('Content-Type: application/json');

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Not logged in']);
    exit;
}

$db   = Database::getInstance();
$user = currentUser();
$role = $user['role'];
$empId = $user['emp_id'];

if (!in_array($role, ['manager', 'hr', 'admin', 'superadmin'], true)) {
    echo json_encode(['total' => 0, 'items' => []]);
    exit;
}

$mgmt = in_array($role, ['admin', 'superadmin'], true);

// FIX (10 Jul 2026): the management branch had no organization scope at
// all — an admin/superadmin saw pending items across every organization,
// not just their own. Mirrors orgScopeClause() usage elsewhere.
[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');
$mgmtCond = "AND $orgClause";
$repCond  = "AND e.reporting_manager_id = ? AND $orgClause";

$leaves = $db->fetchAll(
    "SELECT la.id, la.created_at, CONCAT(e.first_name,' ',e.last_name) AS emp_name, lt.name AS type_name
       FROM leave_applications la
       JOIN employees e ON e.id = la.employee_id
       JOIN leave_types lt ON lt.id = la.leave_type_id
      WHERE la.status = 'pending' " . ($mgmt ? $mgmtCond : $repCond) . "
      ORDER BY la.created_at DESC LIMIT 10",
    $mgmt ? $orgParams : array_merge([$empId], $orgParams)
);

$perms = $db->fetchAll(
    "SELECT pr.id, pr.created_at, CONCAT(e.first_name,' ',e.last_name) AS emp_name
       FROM permission_requests pr
       JOIN employees e ON e.id = pr.employee_id
      WHERE pr.status = 'pending' " . ($mgmt ? $mgmtCond : $repCond) . "
      ORDER BY pr.created_at DESC LIMIT 10",
    $mgmt ? $orgParams : array_merge([$empId], $orgParams)
);

$lates = $db->fetchAll(
    "SELECT lr.id, lr.created_at, CONCAT(e.first_name,' ',e.last_name) AS emp_name
       FROM late_regularizations lr
       JOIN employees e ON e.id = lr.employee_id
      WHERE lr.status = 'pending' " . ($mgmt ? $mgmtCond : $repCond) . "
      ORDER BY lr.created_at DESC LIMIT 10",
    $mgmt ? $orgParams : array_merge([$empId], $orgParams)
);

$items = [];
foreach ($leaves as $l) {
    $items[] = ['badge' => 'warning', 'label' => 'Leave', 'text' => clean($l['emp_name']) . ' – ' . clean($l['type_name']) . ' leave pending',
                'time' => $l['created_at'], 'link' => BASE_URL . '/modules/leave/index.php'];
}
foreach ($perms as $p) {
    $items[] = ['badge' => 'info', 'label' => 'Permission', 'text' => clean($p['emp_name']) . ' – permission request pending',
                'time' => $p['created_at'], 'link' => BASE_URL . '/modules/attendance/permission.php'];
}
foreach ($lates as $lt) {
    $items[] = ['badge' => 'danger', 'label' => 'Late', 'text' => clean($lt['emp_name']) . ' – late mark regularization pending',
                'time' => $lt['created_at'], 'link' => BASE_URL . '/modules/attendance/regularization.php'];
}

usort($items, fn($a, $b) => strtotime($b['time']) <=> strtotime($a['time']));
$items = array_slice($items, 0, 10);

echo json_encode([
    'leave'      => count($leaves),
    'permission' => count($perms),
    'late'       => count($lates),
    'total'      => count($leaves) + count($perms) + count($lates),
    'items'      => $items,
]);