<?php
require __DIR__ . '/../src/auth.php';
require_login();
require __DIR__ . '/../src/db.php';
$user = current_user();

// 1. INCREASE LIMIT TO 50 (So scrolling is useful)
$stmt = $pdo->query('SELECT r.id, r.filename, r.service_provider, r.uploaded_at, u.username 
                     FROM raw_reports r 
                     LEFT JOIN users u ON r.uploaded_by = u.id 
                     ORDER BY r.uploaded_at DESC LIMIT 50');
$recent = $stmt->fetchAll();

// Provider Stats
$pStmt = $pdo->query("SELECT service_provider, COUNT(*) as cnt, MAX(uploaded_at) as last_seen FROM raw_reports WHERE service_provider IS NOT NULL AND service_provider != '' GROUP BY service_provider");
$providerStats = $pStmt->fetchAll();

// Top PMS backlog (Sum)
$stmt = $pdo->query('SELECT prop_name, SUM(count_value) as total FROM pms_backlog GROUP BY prop_name ORDER BY total DESC LIMIT 8');
$topPMS = $stmt->fetchAll();
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Dashboard | Report System</title>
  
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
  
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
  
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <style>
    body {
      font-family: 'Inter', sans-serif;
      background-color: #f3f6f9;
      color: #344767;
    }
    
    /* Navbar Styling */
    .navbar {
      background: linear-gradient(90deg, #1e293b 0%, #334155 100%);
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
      padding-top: 0.75rem;
      padding-bottom: 0.75rem;
    }
    .navbar-brand {
      color: #fff !important;
      font-weight: 600;
      letter-spacing: 0.5px;
    }
    
    /* Card Styling */
    .card {
      border: none;
      border-radius: 12px;
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
      transition: transform 0.2s;
      background: #fff;
    }
    .card-header {
      background-color: transparent;
      border-bottom: 1px solid #f0f2f5;
      padding: 1.25rem;
      font-weight: 600;
      color: #1e293b;
    }
    .card-body {
      padding: 1.25rem;
    }

    /* Table Styling */
    .table thead th {
      text-transform: uppercase;
      font-size: 0.75rem;
      letter-spacing: 0.5px;
      color: #8898aa;
      font-weight: 700;
      border-bottom: 2px solid #f0f2f5;
      padding-bottom: 10px;
      
      /* STICKY HEADER FOR SCROLLING */
      position: sticky;
      top: 0;
      background-color: #fff; /* White background to hide scrolling content */
      z-index: 10;
      box-shadow: 0 2px 2px -1px rgba(0,0,0,0.05);
    }
    .table tbody td {
      vertical-align: middle;
      padding: 12px 10px;
      border-bottom: 1px solid #f0f2f5;
      font-size: 0.9rem;
    }
    .table-hover tbody tr:hover {
      background-color: #f8f9fa;
    }

    /* SCROLLABLE TABLE CONTAINER */
    .table-scrollable {
        max-height: 400px; /* Adjust height as needed */
        overflow-y: auto;
        scrollbar-width: thin; /* Firefox */
        scrollbar-color: #cbd5e1 #f1f5f9;
    }
    /* Webkit Scrollbar Styling */
    .table-scrollable::-webkit-scrollbar {
        width: 8px;
    }
    .table-scrollable::-webkit-scrollbar-track {
        background: #f1f5f9;
    }
    .table-scrollable::-webkit-scrollbar-thumb {
        background-color: #cbd5e1;
        border-radius: 4px;
    }

    /* Badges & Buttons */
    .badge-provider {
      background-color: #e0e7ff;
      color: #4338ca;
      padding: 6px 10px;
      border-radius: 20px;
      font-weight: 500;
      font-size: 0.75rem;
    }
    .btn-action {
      border-radius: 8px;
      transition: all 0.2s;
    }
    .btn-action:hover {
      transform: translateY(-2px);
    }
  </style>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark border-bottom">
  <div class="container">
    <a class="navbar-brand d-flex align-items-center" href="dashboard.php">
      <i class="bi bi-grid-1x2-fill me-2"></i> Report System
    </a>
    
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
      <span class="navbar-toggler-icon"></span>
    </button>
    
    <div class="collapse navbar-collapse justify-content-end" id="navbarNav">
      <div class="d-flex gap-2 flex-wrap">
         <a href="view_wakeup.php" class="btn btn-sm btn-outline-warning text-light d-flex align-items-center">
            <i class="bi bi-alarm me-2"></i> Wakeup Errors
         </a>
         <a href="view_offline.php" class="btn btn-sm btn-outline-light d-flex align-items-center">
            <i class="bi bi-router me-2"></i> Offline RT
         </a>
         <a href="export_all_text.php" class="btn btn-sm btn-light d-flex align-items-center text-dark">
            <i class="bi bi-file-text me-2"></i> Export All
         </a>
         <a href="providers.php" class="btn btn-sm btn-outline-info d-flex align-items-center">
            <i class="bi bi-gear me-2"></i> Settings
         </a>
         <a href="upload.php" class="btn btn-sm btn-primary d-flex align-items-center shadow-sm">
            <i class="bi bi-cloud-upload me-2"></i> Upload
         </a>
         <a href="logout.php" class="btn btn-sm btn-outline-secondary text-light border-secondary d-flex align-items-center">
            <i class="bi bi-box-arrow-right me-2"></i> Logout
         </a>
      </div>
    </div>
  </div>
</nav>

<div class="container py-4">
  
  <div class="row mb-4">
      <div class="col-12">
          <h4 class="fw-bold text-dark">Dashboard Overview</h4>
          <p class="text-muted small">Welcome back, <?= htmlspecialchars($user['username']) ?>. Here is what's happening today.</p>
      </div>
  </div>

  <div class="row mb-4">
    <div class="col-lg-4 mb-4 mb-lg-0">
      <div class="card h-100">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span><i class="bi bi-building me-2 text-primary"></i>Service Providers</span>
            <span class="badge bg-primary rounded-pill"><?= count($providerStats) ?></span>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table mb-0">
                    <thead>
                        <tr>
                            <th class="ps-4">Provider</th>
                            <th class="text-center">Reports</th>
                            <th class="text-end pe-4">Last Seen</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if(empty($providerStats)): ?>
                        <tr><td colspan="3" class="text-center text-muted py-4">No data yet</td></tr>
                    <?php else: ?>
                        <?php foreach($providerStats as $s): ?>
                            <tr>
                                <td class="ps-4 fw-bold text-dark"><?= htmlspecialchars($s['service_provider']) ?></td>
                                <td class="text-center"><span class="badge bg-light text-dark border"><?= $s['cnt'] ?></span></td>
                                <td class="text-end pe-4 text-muted small"><?= date('M d, H:i', strtotime($s['last_seen'])) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
      </div>
    </div>

    <div class="col-lg-8">
      <div class="card h-100">
        <div class="card-header">
            <span><i class="bi bi-bar-chart-fill me-2 text-success"></i>Top PMS Backlog (Sum)</span>
        </div>
        <div class="card-body">
          <canvas id="pmsChart" height="120"></canvas>
        </div>
      </div>
    </div>
  </div>

  <div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
  <span>Recent Reports (Last 50)</span>

  <!-- 🔥 DELETE ALL BUTTON ADDED HERE -->
  <div class="d-flex gap-2">
    <a href="upload.php" class="btn btn-sm btn-link">Upload New</a>

    <a href="delete_row.php?table=raw_reports&delete_all=1"
       class="btn btn-sm btn-outline-danger"
       onclick="return confirm('⚠️ This will permanently delete ALL reports. This cannot be undone. Are you sure?');">
       <i class="bi bi-trash3"></i> Delete All
    </a>
  </div>
</div>
    <div class="card-body p-0">
      <div class="table-responsive table-scrollable">
        <table class="table table-hover mb-0 align-middle">
            <thead>
                <tr>
                    <th class="ps-4">File / Type</th>
                    <th>Provider</th>
                    <th>Uploaded At</th>
                    <th class="text-end pe-4">Actions</th>
                </tr>
            </thead>
            <tbody>
              <?php if(empty($recent)): ?>
                  <tr><td colspan="4" class="text-center py-5 text-muted">No reports uploaded yet.</td></tr>
              <?php else: ?>
                  <?php foreach($recent as $r): ?>
                    <tr>
                      <td class="ps-4">
                          <div class="d-flex align-items-center">
                              <div class="bg-light rounded p-2 me-3 text-primary">
                                  <i class="bi bi-file-earmark-text-fill fs-5"></i>
                              </div>
                              <div>
                                  <div class="fw-bold text-dark"><?= htmlspecialchars($r['filename'] ?: 'API Upload') ?></div>
                                  <div class="small text-muted">By <?= htmlspecialchars($r['username'] ?? 'Unknown') ?></div>
                              </div>
                          </div>
                      </td>
                      <td>
                          <span class="badge-provider">
                              <?= htmlspecialchars($r['service_provider']) ?>
                          </span>
                      </td>
                      <td class="text-secondary small">
                          <?= date('M d, Y h:i A', strtotime($r['uploaded_at'])) ?>
                      </td>
                      <td class="text-end pe-4">
                          <div class="btn-group">
                              <a class="btn btn-sm btn-outline-primary btn-action" 
                                 href="view_report.php?id=<?=$r['id']?>" 
                                 title="View Details">
                                 <i class="bi bi-eye"></i> View
                              </a>
                              <a class="btn btn-sm btn-outline-danger btn-action ms-1" 
                                 href="delete_row.php?table=raw_reports&id=<?=$r['id']?>" 
                                 onclick="return confirm('Are you sure you want to delete this entire report? This cannot be undone.');"
                                 title="Delete Report">
                                 <i class="bi bi-trash"></i>
                              </a>
                          </div>
                      </td>
                    </tr>
                  <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<script>
const labels = <?=json_encode(array_map(fn($r)=>substr($r['prop_name']??'',0,20), $topPMS))?>;
const data = <?=json_encode(array_map(fn($r)=>intval($r['total']), $topPMS))?>;
const ctx = document.getElementById('pmsChart');

if(ctx) {
    new Chart(ctx, {
      type: 'bar',
      data: { 
          labels: labels, 
          datasets: [{ 
              label: 'Backlog Count', 
              data: data,
              backgroundColor: 'rgba(54, 162, 235, 0.7)',
              borderColor: 'rgba(54, 162, 235, 1)',
              borderWidth: 1,
              borderRadius: 6,
              barPercentage: 0.6
          }] 
      },
      options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: { legend: { display: false } },
          scales: {
              y: { beginAtZero: true, grid: { borderDash: [2, 2], color: '#f0f2f5' } },
              x: { grid: { display: false } }
          }
      }
    });
}
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>