<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include('includes/db.php'); // PDO connection

// ---------------- Auto Logout for Inactivity ----------------
$timeout_duration = 43200; // 12 hours
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
    session_start();
    $_SESSION['flash'] = [
        "message" => "You have been logged out due to inactivity.",
        "color"   => "#dc3545"
    ];
    header("Location: login.php");
    exit;
}
$_SESSION['LAST_ACTIVITY'] = time();

// ---------------- Access Control ----------------
if (!isset($_SESSION['user_role'])) {
    $_SESSION['flash'] = ["message" => "Please log in first!", "color" => "#dc3545"];
    header("Location: login.php");
    exit;
}

if ($_SESSION['user_role'] !== 'Doctor') {
    $_SESSION['flash'] = ["message" => "Access denied! Only Doctors allowed.", "color" => "#dc3545"];
    header("Location: login.php");
    exit;
}

// ---------------- User & Facility Info ----------------
$username        = $_SESSION['username'] ?? 'Doctor';
$facility_name   = $_SESSION['user_facility_name'] ?? 'N/A';
$facility_id     = intval($_SESSION['facility_id'] ?? 0);

if ($facility_id <= 0) {
    die("Facility not assigned to doctor.");
}

// ---------------- Dashboard Stats ----------------

// 1. Total Patients (facility scoped)
$stmt = $pdo->prepare("
    SELECT COUNT(DISTINCT id) 
    FROM patients 
    WHERE facility_id = ?
");
$stmt->execute([$facility_id]);
$totalPatients = $stmt->fetchColumn() ?: 0;

// 2. Total Visits (facility scoped)
$stmt = $pdo->prepare("
    SELECT COUNT(*) 
    FROM visits 
    WHERE facility_id = ?
");
$stmt->execute([$facility_id]);
$totalVisits = $stmt->fetchColumn() ?: 0;

// 3. Total Visit Tickets (facility scoped)
$stmt = $pdo->prepare("
    SELECT COUNT(*) 
    FROM visit_tickets vt
    JOIN visits v ON v.id = vt.visit_id
    WHERE v.facility_id = ?
");
$stmt->execute([$facility_id]);
$totalVisitTickets = $stmt->fetchColumn() ?: 0;

// 4. Upcoming Appointments (facility scoped)
$stmt = $pdo->prepare("
    SELECT COUNT(*) 
    FROM visits 
    WHERE visit_date > NOW() 
      AND status = 'open'
      AND facility_id = ?
");
$stmt->execute([$facility_id]);
$upcomingAppointments = $stmt->fetchColumn() ?: 0;

// 5. Pending Lab Results (facility scoped)
$stmt = $pdo->prepare("
    SELECT COUNT(lo.id)
    FROM lab_orders lo
    JOIN visit_tickets vt ON vt.id = lo.visit_ticket_id
    JOIN visits v ON v.id = vt.visit_id
    WHERE lo.status = 'pending'
      AND v.facility_id = ?
");
$stmt->execute([$facility_id]);
$pendingLabResults = $stmt->fetchColumn() ?: 0;

// 6. Recent Visits (facility scoped)
$stmt = $pdo->prepare("
    SELECT 
        v.visit_number,
        p.first_name,
        p.last_name,
        v.visit_date,
        v.status,
        v.id AS visit_id
    FROM visits v
    JOIN patients p ON p.id = v.patient_id
    WHERE v.facility_id = ?
    ORDER BY v.visit_date DESC
    LIMIT 10
");
$stmt->execute([$facility_id]);
$recentVisits = $stmt->fetchAll(PDO::FETCH_ASSOC);

ob_end_flush();
?>


<?php include('includes/header.php'); ?>

<!-- navbar-fixed-top-->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
  <?php include('includes/navbar.php'); ?>
</nav>

<!-- main menu-->
<div data-scroll-to-active="true" class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
  <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
  <div class="content-wrapper">
    <div class="content-header row">
      <div class="col-md-12">
        <h3 class="content-header-title">Doctor Dashboard</h3>
        <!--<p>-->
        <!--  Welcome, <strong><?= htmlspecialchars($username) ?></strong> |-->
        <!--  Facility: <strong><?= htmlspecialchars($facility_name) ?></strong>-->
        <!--</p>-->
      </div>
    </div>

    <div class="content-body">

      <!-- Doctor Stats -->
      <div class="row">

        <div class="col-md-3">
          <div class="card text-center p-3">
            <h4>Total Patients</h4>
            <p><?= $totalPatients ?></p>
          </div>
        </div>

        <div class="col-md-3">
          <div class="card text-center p-3">
            <h4>Total Visits</h4>
            <p><?= $totalVisits ?></p>
          </div>
        </div>

        <div class="col-md-3">
          <div class="card text-center p-3">
            <h4>Total Visit Tickets</h4>
            <p><?= $totalVisitTickets ?></p>
          </div>
        </div>

        <div class="col-md-3">
          <div class="card text-center p-3">
            <h4>Upcoming Appointments</h4>
            <p><?= $upcomingAppointments ?></p>
          </div>
        </div>

      </div>
      <!-- / Doctor Stats -->

      <div class="row mt-4">
        <div class="col-md-12">
          <div class="card p-3">
            <h4>Pending Lab Results: <?= $pendingLabResults ?></h4>
            <h4 class="mt-3">Recent Visits</h4>
            <!--<table class="table table-bordered table-striped">-->
            <!--  <thead>-->
            <!--    <tr>-->
            <!--      <th>Visit Number</th>-->
            <!--      <th>Patient</th>-->
            <!--      <th>Visit Date</th>-->
            <!--      <th>Status</th>-->
            <!--      <th>Actions</th>-->
            <!--    </tr>-->
            <!--  </thead>-->
            <!--  <tbody>-->
            <!--    <?php foreach ($recentVisits as $visit): ?>-->
            <!--      <tr>-->
            <!--        <td><?= htmlspecialchars($visit['visit_number']) ?></td>-->
            <!--        <td><?= htmlspecialchars($visit['first_name'] . ' ' . $visit['last_name']) ?></td>-->
            <!--        <td><?= htmlspecialchars($visit['visit_date']) ?></td>-->
            <!--        <td><?= htmlspecialchars(ucfirst($visit['status'])) ?></td>-->
            <!--        <td><a href="visit_ticket.php?id=<?= $visit['visit_id'] ?>" class="btn btn-sm btn-primary">View</a></td>-->
            <!--      </tr>-->
            <!--    <?php endforeach; ?>-->
            <!--  </tbody>-->
            <!--</table>-->
          </div>
        </div>
      </div>

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

<?php include('includes/footer.php'); ?>
