<?php
require __DIR__ . '/../src/auth.php';
require_login();
require __DIR__ . '/../src/db.php';

$reportId = (int)($_GET['id'] ?? 0);
if (!$reportId) { header('Location: dashboard.php'); exit; }

// 1. Fetch Report Metadata & Custom Provider Message
$stmt = $pdo->prepare('
    SELECT r.*, ps.custom_message 
    FROM raw_reports r 
    LEFT JOIN provider_settings ps ON r.service_provider = ps.provider_name 
    WHERE r.id = ?
');
$stmt->execute([$reportId]);
$report = $stmt->fetch();

if (!$report) { echo "Report not found"; exit; }

// 2. Fetch Data Sections
$pms = $pdo->prepare('SELECT * FROM pms_backlog WHERE report_id = ? ORDER BY count_value DESC');
$pms->execute([$reportId]);
$pmsRows = $pms->fetchAll();

$offline = $pdo->prepare('SELECT * FROM offline_rt1000 WHERE report_id = ?');
$offline->execute([$reportId]);
$offlineRows = $offline->fetchAll();

$cdr = $pdo->prepare('SELECT * FROM cdr_status WHERE report_id = ?');
$cdr->execute([$reportId]);
$cdrRows = $cdr->fetchAll();

$wakeup = $pdo->prepare('SELECT * FROM wakeup_errors WHERE report_id = ? ORDER BY created_at DESC');
$wakeup->execute([$reportId]);
$wakeupRows = $wakeup->fetchAll();


// Helper for delete link - STYLED as an Icon Button
function deleteBtn($table, $id, $reportId, $tabName) {
    return "<a href='delete_row.php?table={$table}&id={$id}&report_id={$reportId}&tab={$tabName}' 
            class='btn btn-sm btn-light text-danger border-0 shadow-sm' 
            style='--bs-btn-padding-y: .25rem; --bs-btn-padding-x: .5rem; font-size: .875rem;'
            title='Delete Row'
            onclick=\"return confirm('Delete this row?');\"><i class='bi bi-trash-fill'></i></a>";
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>View Report #<?=$reportId?> | 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">

  <style>
    body {
      font-family: 'Inter', sans-serif;
      background-color: #f3f6f9;
      color: #344767;
    }

    /* Navbar */
    .navbar {
      background: linear-gradient(90deg, #1e293b 0%, #334155 100%);
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }
    .navbar-brand { font-weight: 600; letter-spacing: 0.5px; }

    /* Cards */
    .card {
      border: none;
      border-radius: 12px;
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
      background: #fff;
    }
    
    /* Metadata Section */
    .report-meta-card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 2px 4px rgba(0,0,0,0.04);
        border-left: 5px solid #4338ca;
    }

    /* Tabs */
    .nav-tabs {
        border-bottom: 2px solid #e9ecef;
    }
    .nav-tabs .nav-link {
        border: none;
        color: #6c757d;
        font-weight: 500;
        padding: 10px 20px;
        transition: all 0.2s;
    }
    .nav-tabs .nav-link:hover {
        color: #4338ca;
        background: transparent;
    }
    .nav-tabs .nav-link.active {
        color: #4338ca;
        border-bottom: 3px solid #4338ca;
        background: transparent;
    }

    /* Tables */
    .table-container {
        background: white;
        border-radius: 0 0 12px 12px;
        padding: 1rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
    }
    .table thead th {
        text-transform: uppercase;
        font-size: 0.75rem;
        color: #8898aa;
        font-weight: 700;
        border-bottom: 2px solid #f0f2f5;
        padding-bottom: 12px;
    }
    .table tbody td {
        vertical-align: middle;
        padding: 12px 10px;
        border-bottom: 1px solid #f0f2f5;
        font-size: 0.9rem;
    }
    .badge-provider {
        background-color: #e0e7ff;
        color: #4338ca;
        padding: 5px 12px;
        border-radius: 20px;
        font-weight: 600;
        font-size: 0.8rem;
    }
    .badge-count {
        font-size: 0.8rem;
        padding: 4px 8px;
        border-radius: 6px;
    }
  </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>
    <div class="ms-auto">
        <a class="btn btn-sm btn-outline-light" href="dashboard.php">
            <i class="bi bi-arrow-left me-1"></i> Back to Dashboard
        </a>
    </div>
  </div>
</nav>

<div class="container py-4">

  <div class="report-meta-card d-flex flex-column flex-md-row justify-content-between align-items-md-center">
      <div>
          <div class="text-muted small text-uppercase fw-bold mb-1">Report Details</div>
          <h4 class="fw-bold mb-1 d-flex align-items-center">
              <?=htmlspecialchars($report['filename'])?>
              <span class="ms-3 badge-provider"><?= htmlspecialchars($report['service_provider'] ?? 'Unknown') ?></span>
          </h4>
          <div class="text-muted small mt-2">
              <i class="bi bi-calendar3 me-1"></i> Uploaded: <?=htmlspecialchars($report['uploaded_at'])?>
          </div>
      </div>
      
      <div class="d-flex gap-2 mt-3 mt-md-0">
         <a class="btn btn-sm btn-success shadow-sm" href="export_excel.php?id=<?=$reportId?>">
             <i class="bi bi-file-earmark-spreadsheet me-1"></i> Export Excel
         </a>
         <a class="btn btn-sm btn-danger shadow-sm" href="export_pdf.php?id=<?=$reportId?>">
             <i class="bi bi-file-earmark-pdf me-1"></i> Export PDF
         </a>
      </div>
  </div>

  <?php if (!empty($report['custom_message'])): ?>
      <div class="alert alert-warning shadow-sm border-0 border-start border-4 border-warning d-flex align-items-center mb-4" role="alert">
          <i class="bi bi-exclamation-triangle-fill fs-4 me-3 text-warning"></i>
          <div>
              <div class="fw-bold text-dark">Provider Note</div>
              <div class="small"><?= nl2br(htmlspecialchars($report['custom_message'])) ?></div>
          </div>
      </div>
  <?php endif; ?>

  <div class="card shadow-sm">
      <div class="card-header bg-white pb-0 pt-3 px-3 border-0">
          <ul class="nav nav-tabs" id="tabs" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" data-bs-toggle="tab" href="#pms">
                    <i class="bi bi-list-task me-1"></i> PMS Backlog <span class="badge bg-light text-dark ms-1"><?=count($pmsRows)?></span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="tab" href="#offline">
                    <i class="bi bi-router me-1"></i> Offline RT <span class="badge bg-light text-dark ms-1"><?=count($offlineRows)?></span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="tab" href="#cdr">
                    <i class="bi bi-telephone me-1"></i> CDR Status <span class="badge bg-light text-dark ms-1"><?=count($cdrRows)?></span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="tab" href="#wakeup">
                    <i class="bi bi-alarm me-1"></i> Wakeup Errors <span class="badge bg-light text-dark ms-1"><?=count($wakeupRows)?></span>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="tab" href="#raw">
                    <i class="bi bi-code-slash me-1"></i> Raw Content
                </a>
            </li>
          </ul>
      </div>

      <div class="card-body p-0">
          <div class="tab-content">
            
            <div id="pms" class="tab-pane fade show active">
              <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th class="ps-4">Prop ID</th>
                            <th>Property Name</th>
                            <th>Count</th>
                            <th class="text-end pe-4">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if(empty($pmsRows)): ?>
                        <tr><td colspan="4" class="text-center py-5 text-muted">No records found.</td></tr>
                    <?php else: ?>
                        <?php foreach($pmsRows as $r): ?>
                          <tr class="<?= ($r['count_value']>=50 ? 'table-warning bg-opacity-10' : '') ?>">
                            <td class="ps-4 fw-bold text-secondary"><?=htmlspecialchars($r['property_id'])?></td>
                            <td><?=htmlspecialchars($r['prop_name'])?></td>
                            <td>
                                <span class="badge-count bg-<?= ($r['count_value']>=50 ? 'danger' : 'success') ?> text-white">
                                    <?=htmlspecialchars($r['count_value'])?>
                                </span>
                            </td>
                            <td class="text-end pe-4"><?= deleteBtn('pms_backlog', $r['id'], $reportId, 'pms') ?></td>
                          </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
              </div>
            </div>

            <div id="offline" class="tab-pane fade">
              <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th class="ps-4">Prop ID</th>
                            <th>Property Name</th>
                            <th>RT Name</th>
                            <th class="text-end pe-4">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach($offlineRows as $r): ?>
                      <tr>
                        <td class="ps-4 fw-bold text-secondary"><?=htmlspecialchars($r['property_id'])?></td>
                        <td><?=htmlspecialchars($r['prop_name'])?></td>
                        <td class="text-danger font-monospace"><?=htmlspecialchars($r['rt_name'])?></td>
                        <td class="text-end pe-4"><?= deleteBtn('offline_rt1000', $r['id'], $reportId, 'offline') ?></td>
                      </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
              </div>
            </div>

            <div id="cdr" class="tab-pane fade">
              <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th class="ps-4">Prop ID</th>
                            <th>Property Name</th>
                            <th>PBX Details</th>
                            <th>Codes</th>
                            <th>Last Posted</th>
                            <th class="text-end pe-4">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach($cdrRows as $r): ?>
                      <tr>
                        <td class="ps-4 fw-bold text-secondary"><?=htmlspecialchars($r['property_id'])?></td>
                        <td><?=htmlspecialchars($r['prop_name'])?></td>
                        <td>
                            <div class="small fw-bold"><?=htmlspecialchars($r['pbx_type'])?></div>
                            <div class="text-muted small">Num: <?=htmlspecialchars($r['pbx_number'])?></div>
                        </td>
                        <td class="small">
                            <div>Ent: <?=htmlspecialchars($r['enterprise_code'])?></div>
                            <div>Grp: <?=htmlspecialchars($r['group_code'])?></div>
                        </td>
                        <td class="text-muted small"><?=htmlspecialchars($r['last_posted_on'])?></td>
                        <td class="text-end pe-4"><?= deleteBtn('cdr_status', $r['id'], $reportId, 'cdr') ?></td>
                      </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
              </div>
            </div>

            <div id="wakeup" class="tab-pane fade">
              <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th class="ps-4">Prop ID</th>
                            <th>Property Name</th>
                            <th>Room</th>
                            <th>Schedule / Wakeup</th>
                            <th>Status</th>
                            <th class="text-end pe-4">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach($wakeupRows as $r): ?>
                      <tr>
                        <td class="ps-4 fw-bold text-secondary"><?=htmlspecialchars($r['property_id'])?></td>
                        <td>
                            <?=htmlspecialchars($r['prop_name'])?>
                            <div class="small text-muted"><?=htmlspecialchars($r['pbx_type'])?></div>
                        </td>
                        <td class="fw-bold"><?=htmlspecialchars($r['room_number'])?></td>
                        <td class="small">
                            <div><i class="bi bi-clock me-1"></i> Sch: <?=htmlspecialchars($r['schedule_time'])?></div>
                            <div class="text-muted"><i class="bi bi-bell me-1"></i> Wak: <?=htmlspecialchars($r['wakeup_time'])?></div>
                        </td>
                        <td>
                            <span class="badge bg-light text-danger border border-danger border-opacity-25">
                                <?=htmlspecialchars($r['status_text'])?>
                            </span>
                            <div class="small text-muted mt-1">Att: <?=htmlspecialchars($r['attempts'])?></div>
                        </td>
                        <td class="text-end pe-4"><?= deleteBtn('wakeup_errors', $r['id'], $reportId, 'wakeup') ?></td>
                      </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
              </div>
            </div>

            <div id="raw" class="tab-pane fade">
              <div class="p-4">
                  <pre class="bg-dark text-light p-3 rounded" style="font-size: 0.85rem; max-height: 500px; overflow-y: auto;"><?=htmlspecialchars($report['content'])?></pre>
              </div>
            </div>

          </div>
      </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
document.addEventListener("DOMContentLoaded", function() {
    var hash = window.location.hash;
    if (hash) {
        var triggerEl = document.querySelector('#tabs a[href="' + hash + '"]');
        if (triggerEl) {
            var tab = new bootstrap.Tab(triggerEl);
            tab.show();
        }
    }
});
</script>
</body>
</html>