<?php
require_once __DIR__ . '/core/auth.php';
$user = require_login();
$pdo = pdo();

$params = [];
$agentFilter = '';
if ($user['role'] !== 'admin') {
    $agentFilter = " AND vr.agent_name IN (
        SELECT agent_name FROM user_agent_assignments WHERE user_id = :uid
        UNION
        SELECT agent_name FROM agentsmrd WHERE rsm_name = :full_name
    )";
    $params[':uid'] = $user['id'];
    $params[':full_name'] = $user['full_name'];
}

$stmt = $pdo->prepare("SELECT COUNT(*) FROM visit_reports vr WHERE DATE(vr.created_at) = CURDATE() {$agentFilter}");
$stmt->execute($params);
$todayCount = (int) $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM visit_reports vr WHERE YEAR(vr.created_at)=YEAR(CURDATE()) AND MONTH(vr.created_at)=MONTH(CURDATE()) {$agentFilter}");
$stmt->execute($params);
$monthCount = (int) $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM visit_reports vr WHERE vr.status='completed' {$agentFilter}");
$stmt->execute($params);
$completedCount = (int) $stmt->fetchColumn();

$agents = get_accessible_agents($pdo, $user);
$stmt = $pdo->prepare("SELECT vr.*, u.full_name
    FROM visit_reports vr
    LEFT JOIN users u ON u.id = vr.user_id
    WHERE 1=1 {$agentFilter}
    ORDER BY vr.created_at DESC
    LIMIT 8");
$stmt->execute($params);
$recentReports = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - <?= e(app_name()) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/app.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg bg-white border-bottom sticky-top">
    <div class="container-fluid px-3">
        <a class="navbar-brand fw-bold" href="dashboard.php"><?= e(app_name()) ?></a>
        <div class="d-flex gap-2 align-items-center">
            <span class="badge text-bg-light text-dark"><?= e($user['full_name']) ?> (<?= e(strtoupper($user['role'])) ?>)</span>
            <a href="logout.php" class="btn btn-outline-danger btn-sm">Logout</a>
        </div>
    </div>
</nav>
<div class="container py-4">
    <div class="d-flex flex-wrap gap-2 justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-1">Dashboard</h1>
            <p class="text-muted mb-0">Track daily and monthly reporting activity.</p>
        </div>
        <div class="d-flex gap-2">
            <a href="report_wizard.php" class="btn btn-primary">+ New Field Report</a>
            <a href="reports.php" class="btn btn-outline-primary">Reports</a>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-12 col-md-3"><div class="card stats-card"><div class="card-body"><div class="text-muted small">Reports Today</div><div class="display-6 fw-bold"><?= $todayCount ?></div></div></div></div>
        <div class="col-12 col-md-3"><div class="card stats-card"><div class="card-body"><div class="text-muted small">Reports This Month</div><div class="display-6 fw-bold"><?= $monthCount ?></div></div></div></div>
        <div class="col-12 col-md-3"><div class="card stats-card"><div class="card-body"><div class="text-muted small">Completed Reports</div><div class="display-6 fw-bold"><?= $completedCount ?></div></div></div></div>
        <div class="col-12 col-md-3"><div class="card stats-card"><div class="card-body"><div class="text-muted small">Accessible DB Names</div><div class="display-6 fw-bold"><?= count($agents) ?></div></div></div></div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h2 class="h5 mb-0">Recent Reports</h2>
            <a href="reports.php" class="btn btn-sm btn-outline-secondary">Open full log</a>
        </div>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Date of Visit</th>
                        <th>DB Name</th>
                        <th>Visit Type</th>
                        <th>Status</th>
                        <th>Prepared By</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$recentReports): ?>
                    <tr><td colspan="7" class="text-center text-muted py-4">No reports yet.</td></tr>
                <?php endif; ?>
                <?php foreach ($recentReports as $row): ?>
                    <tr>
                        <td>#<?= (int) $row['id'] ?></td>
                        <td><?= e($row['date_of_visit']) ?></td>
                        <td><?= e($row['agent_name']) ?></td>
                        <td><?= e($row['visited_type']) ?></td>
                        <td><span class="badge <?= $row['status'] === 'completed' ? 'text-bg-success' : 'text-bg-warning' ?>"><?= e(ucfirst($row['status'])) ?></span></td>
                        <td><?= e($row['full_name'] ?? '-') ?></td>
                        <td class="text-end">
                            <a href="report_view.php?id=<?= (int) $row['id'] ?>" class="btn btn-sm btn-outline-secondary">View</a>
                            <a href="report_wizard.php?id=<?= (int) $row['id'] ?>" class="btn btn-sm btn-outline-primary">Edit</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>
