<?php
require_once __DIR__ . '/config/config.php';
require_login();
$u = current_user();

$canViewAll = has_permission($pdo, $u, 'requisitions.view_all');
$canViewMainStore = has_permission($pdo, $u, 'main_store.view');
$deptId = $u['department_id'];

$itemCount = $pdo->query("SELECT COUNT(*) FROM items WHERE is_active=1")->fetchColumn();

// Outlets: scoped to the user's own department unless they can see everything
if ($canViewAll || has_permission($pdo, $u, 'outlets.manage')) {
    $outletCount = $pdo->query("SELECT COUNT(*) FROM outlets WHERE is_active=1")->fetchColumn();
} elseif ($deptId !== null) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM outlets WHERE is_active=1 AND department_id = ?");
    $stmt->execute([$deptId]);
    $outletCount = $stmt->fetchColumn();
} else {
    $outletCount = $pdo->query("SELECT COUNT(*) FROM outlets WHERE is_active=1")->fetchColumn();
}

$lowStock = $canViewMainStore
    ? $pdo->query("SELECT COUNT(*) FROM items i JOIN main_store_stock s ON s.item_id=i.id WHERE s.quantity <= i.reorder_level")->fetchColumn()
    : null;

$expiringSoon = $canViewMainStore ? count(get_expiring_batches($pdo, 30)) : null;

// Pending Purchase Requisitions - scoped to own department + own requests unless view_all
if ($canViewAll) {
    $pendingPR = $pdo->query("SELECT COUNT(*) FROM purchase_requisitions WHERE status='pending'")->fetchColumn();
} else {
    $sql = "SELECT COUNT(*) FROM purchase_requisitions WHERE status='pending' AND (requested_by = ?"
         . ($deptId !== null ? " OR department_id = ?" : " OR department_id IS NULL") . ")";
    $params = [$u['id']];
    if ($deptId !== null) $params[] = $deptId;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $pendingPR = $stmt->fetchColumn();
}

// Pending Store Requisitions - scoped via the outlet's department unless view_all
if ($canViewAll) {
    $pendingSR = $pdo->query("SELECT COUNT(*) FROM store_requisitions WHERE status='pending'")->fetchColumn();
} else {
    $sql = "SELECT COUNT(*) FROM store_requisitions sr JOIN outlets o ON o.id = sr.outlet_id
            WHERE sr.status='pending' AND (sr.requested_by = ?"
         . ($deptId !== null ? " OR o.department_id = ?" : " OR o.department_id IS NULL") . ")";
    $params = [$u['id']];
    if ($deptId !== null) $params[] = $deptId;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $pendingSR = $stmt->fetchColumn();
}

// Requisitions awaiting THIS user's approval action, also scoped to their department
$myPendingPRSql = "
  SELECT pr.*, u.username as requester FROM purchase_requisitions pr
  JOIN users u ON u.id = pr.requested_by
  WHERE pr.status='pending' AND pr.current_stage = (
      SELECT MIN(stage_order) FROM approval_workflows aw WHERE aw.module='purchase_requisition' AND aw.role_required = :role AND aw.is_active=1
  ) AND EXISTS (SELECT 1 FROM approval_workflows aw2 WHERE aw2.module='purchase_requisition' AND aw2.stage_order = pr.current_stage AND aw2.role_required = :role2)";
$myPendingPRParams = ['role' => $u['role'], 'role2' => $u['role']];
if (!$canViewAll) {
    $myPendingPRSql .= " AND (pr.requested_by = :uid OR pr.department_id " . ($deptId !== null ? "= :deptId" : "IS NULL") . ")";
    $myPendingPRParams['uid'] = $u['id'];
    if ($deptId !== null) $myPendingPRParams['deptId'] = $deptId;
}
$myPendingPRSql .= " ORDER BY pr.created_at DESC LIMIT 5";
$myPendingPR = $pdo->prepare($myPendingPRSql);
$myPendingPR->execute($myPendingPRParams);
$myPR = ($u['role']==='superadmin'||$u['role']==='admin') ? [] : $myPendingPR->fetchAll();

// Recent stock movements - full ledger only for those who can see Main Store /
// everything; everyone else only sees movements into/out of their own outlets
if ($canViewMainStore || $canViewAll) {
    $recentTxns = $pdo->query("SELECT st.*, i.name item_name, un.abbreviation unit_abbr
                                FROM stock_transactions st JOIN items i ON i.id=st.item_id
                                LEFT JOIN units un ON un.id = i.unit_id
                                ORDER BY st.created_at DESC LIMIT 8")->fetchAll();
} elseif ($deptId !== null) {
    $stmt = $pdo->prepare("SELECT st.*, i.name item_name, un.abbreviation unit_abbr
                            FROM stock_transactions st JOIN items i ON i.id=st.item_id
                            LEFT JOIN units un ON un.id = i.unit_id
                            WHERE st.location_type='outlet' AND st.location_id IN (SELECT id FROM outlets WHERE department_id = ?)
                            ORDER BY st.created_at DESC LIMIT 8");
    $stmt->execute([$deptId]);
    $recentTxns = $stmt->fetchAll();
} else {
    $stmt = $pdo->prepare("SELECT st.*, i.name item_name, un.abbreviation unit_abbr
                            FROM stock_transactions st JOIN items i ON i.id=st.item_id
                            LEFT JOIN units un ON un.id = i.unit_id
                            WHERE st.created_by = ? ORDER BY st.created_at DESC LIMIT 8");
    $stmt->execute([$u['id']]);
    $recentTxns = $stmt->fetchAll();
}

// Colour + label per stock transaction type, used as a badge in the table below
function txn_badge($type) {
    $map = [
        'grn_in'         => ['bg-emerald-100 text-emerald-700', 'Goods In'],
        'issue_out'      => ['bg-blue-100 text-blue-700', 'Issued Out'],
        'transfer_out'   => ['bg-amber-100 text-amber-700', 'Transfer Out'],
        'transfer_in'    => ['bg-teal-100 text-teal-700', 'Transfer In'],
        'adjustment_in'  => ['bg-purple-100 text-purple-700', 'Adjustment In'],
        'adjustment_out' => ['bg-rose-100 text-rose-700', 'Adjustment Out'],
        'return_out'     => ['bg-red-100 text-red-700', 'Return to Supplier'],
        'waste_out'      => ['bg-orange-100 text-orange-700', 'Waste / Spoilage'],
    ];
    return $map[$type] ?? ['bg-slate-100 text-slate-600', ucfirst(str_replace('_',' ',$type))];
}

$pageTitle = 'Dashboard';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-1">Welcome, <?= e($u['username']) ?></h1>
<p class="text-slate-500 mb-6 text-sm capitalize">Role: <?= e($u['role']) ?><?= !$canViewAll ? ' · showing data for your department' : '' ?></p>

<div class="grid grid-cols-2 <?= $lowStock !== null ? 'md:grid-cols-6' : 'md:grid-cols-4' ?> gap-3 sm:gap-4 mb-8">
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-3 sm:p-5">
    <p class="text-xs text-slate-500">Active Items</p>
    <p class="text-xl sm:text-2xl font-bold mt-1"><?= (int)$itemCount ?></p>
  </div>
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-3 sm:p-5">
    <p class="text-xs text-slate-500"><?= $canViewAll ? 'Outlets' : 'Your Department Outlets' ?></p>
    <p class="text-xl sm:text-2xl font-bold mt-1"><?= (int)$outletCount ?></p>
  </div>
  <?php if ($lowStock !== null): ?>
  <div class="bg-white rounded-xl shadow-sm border border-amber-200 bg-amber-50 p-3 sm:p-5">
    <p class="text-xs text-amber-700">Low Stock Items</p>
    <p class="text-xl sm:text-2xl font-bold mt-1 text-amber-700"><?= (int)$lowStock ?></p>
  </div>
  <div class="bg-white rounded-xl shadow-sm border border-red-200 bg-red-50 p-3 sm:p-5">
    <p class="text-xs text-red-700">Expiring Soon (30d)</p>
    <p class="text-xl sm:text-2xl font-bold mt-1 text-red-700"><?= (int)$expiringSoon ?></p>
  </div>
  <?php endif; ?>
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-3 sm:p-5">
    <p class="text-xs text-slate-500">Pending Purchase Reqs</p>
    <p class="text-xl sm:text-2xl font-bold mt-1"><?= (int)$pendingPR ?></p>
  </div>
  <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-3 sm:p-5">
    <p class="text-xs text-slate-500">Pending Store Reqs</p>
    <p class="text-xl sm:text-2xl font-bold mt-1"><?= (int)$pendingSR ?></p>
  </div>
</div>

<?php if (!empty($myPR)): ?>
<div class="bg-white rounded-xl shadow-sm border border-slate-200 mb-8">
  <div class="px-5 py-4 border-b border-slate-200 font-semibold">Awaiting Your Approval</div>
  <div class="overflow-x-auto"><table class="w-full text-sm">
    <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
      <th class="text-left px-5 py-2">PR Number</th><th class="text-left px-5 py-2">Requested By</th>
      <th class="text-left px-5 py-2">Amount</th><th class="text-left px-5 py-2"></th></tr></thead>
    <tbody>
    <?php foreach ($myPR as $pr): ?>
      <tr class="border-t border-slate-100">
        <td class="px-5 py-2.5"><?= e($pr['pr_number']) ?></td>
        <td class="px-5 py-2.5"><?= e($pr['requester']) ?></td>
        <td class="px-5 py-2.5">₦<?= number_format($pr['total_estimated_cost'],2) ?></td>
        <td class="px-5 py-2.5 text-right">
          <a href="<?= BASE_URL ?>purchase_requisitions/view.php?id=<?= $pr['id'] ?>" class="text-blue-600 hover:underline">Review →</a>
        </td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table></div>
</div>
<?php endif; ?>

<div class="bg-white rounded-xl shadow-sm border border-slate-200">
  <div class="px-5 py-4 border-b border-slate-200 font-semibold">Recent Stock Movements<?= (!$canViewMainStore && !$canViewAll) ? ' (Your Department)' : '' ?></div>
  <div class="overflow-x-auto"><table class="w-full text-sm">
    <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
      <th class="text-left px-5 py-2">Item</th><th class="text-left px-5 py-2">Type</th>
      <th class="text-left px-5 py-2">Qty</th><th class="text-left px-5 py-2">Date</th></tr></thead>
    <tbody>
    <?php foreach ($recentTxns as $t): [$badgeClass, $badgeLabel] = txn_badge($t['txn_type']); ?>
      <tr class="border-t border-slate-100">
        <td class="px-5 py-2.5"><?= e($t['item_name']) ?></td>
        <td class="px-5 py-2.5"><span class="px-2 py-0.5 rounded-full text-xs font-medium <?= $badgeClass ?>"><?= e($badgeLabel) ?></span></td>
        <td class="px-5 py-2.5"><?= number_format($t['quantity'],2) ?> <?= e($t['unit_abbr']) ?></td>
        <td class="px-5 py-2.5 text-slate-500 whitespace-nowrap">
          <?= date('M j, Y', strtotime($t['created_at'])) ?><br>
          <span class="text-xs"><?= date('h:i A', strtotime($t['created_at'])) ?></span>
        </td>
      </tr>
    <?php endforeach; ?>
    <?php if (empty($recentTxns)): ?><tr><td colspan="4" class="px-5 py-6 text-center text-slate-400">No stock movements yet.</td></tr><?php endif; ?>
    </tbody>
  </table></div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
