<?php
session_start();
require_once '../includes/config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'officer') {
  header("Location: ../auth/login.php");
  exit;
}

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? 'Officer';
$today = date('Y-m-d');
$year = date('Y');

// Initial attendance fetch
$stmt = $pdo->prepare("SELECT * FROM attendance WHERE officer_id = ? AND date = ?");
$stmt->execute([$user_id, $today]);
$attendance = $stmt->fetch();

// Handle attendance submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';

  if ($action === 'checkin' && !$attendance) {
    $pdo->prepare("INSERT INTO attendance (officer_id, date, time_in) VALUES (?, ?, NOW())")
        ->execute([$user_id, $today]);
    header("Location: dashboard.php?checkin=1");
    exit;
  } elseif ($action === 'checkout' && $attendance && !$attendance['time_out']) {
    $pdo->prepare("UPDATE attendance SET time_out = NOW() WHERE id = ?")
        ->execute([$attendance['id']]);
    header("Location: dashboard.php?checkout=1");
    exit;
  }
}

// Other data
$year = date('Y');

// Leave balance
$stmt = $pdo->prepare("SELECT * FROM leave_balance WHERE officer_id = ? AND year = ?");
$stmt->execute([$user_id, $year]);
$leaveBalance = $stmt->fetch();

// Recent leave history
$stmt = $pdo->prepare("SELECT * FROM leave_requests WHERE officer_id = ? ORDER BY id DESC LIMIT 5");
$stmt->execute([$user_id]);
$recentLeaves = $stmt->fetchAll();

// Approved leaves for calendar
$stmt = $pdo->prepare("SELECT leave_type, start_date, end_date FROM leave_requests WHERE officer_id = ? AND status = 'approved'");
$stmt->execute([$user_id]);
$calendarLeaves = $stmt->fetchAll();

// Payslip
$stmt = $pdo->prepare("SELECT * FROM payslips WHERE officer_id = ? ORDER BY id DESC LIMIT 1");
$stmt->execute([$user_id]);
$latestPayslip = $stmt->fetch();

// KET
$stmt = $pdo->prepare("SELECT * FROM employment_terms WHERE officer_id = ? ORDER BY id DESC LIMIT 1");
$stmt->execute([$user_id]);
$latestKET = $stmt->fetch();

// Officer Roster
$stmt = $pdo->prepare("
  SELECT r.shift_date, r.shift_type, s.site_name 
  FROM officer_roster r 
  JOIN sites s ON r.site_id = s.id 
  WHERE r.officer_id = ? 
  ORDER BY r.shift_date DESC
");
$stmt->execute([$user_id]);
$allRosters = $stmt->fetchAll();

// Toast
$toastMessage = '';
if (isset($_GET['checkin'])) $toastMessage = "✅ Checked In!";
if (isset($_GET['checkout'])) $toastMessage = "✅ Checked Out!";

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Officer Dashboard</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
 
</style> 
</head>
<body>


<div class="container">
  <div class="wrapper">
    <div class="row">
      <div class="col-md-6">
          <div class="accordion" id="officerAccordion">
              <nav class="navbar navbar-dark bg-dark px-4 mb-4">
                  <span class="navbar-brand">👮 Welcome, <?= htmlspecialchars($username) ?></span>
                  <a class="btn btn-outline-light btn-sm" href="../auth/logout.php">Logout</a>
              </nav>

                <!-- Attendance -->
                <div class="accordion-item">
                  <h2 class="accordion-header" id="headingAttendance">
                    <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseAttendance" aria-expanded="true">
                      🕒 Attendance
                    </button>
                  </h2>
                  <div id="collapseAttendance" class="accordion-collapse collapse show">
                    <div class="accordion-body">
                      <div class="card-box text-center">
                        <h5 class="text-primary mb-3"><?= $today ?></h5>
                        <p>Check-In: <?= $attendance['time_in'] ?? '<span class="text-muted">Not marked</span>' ?></p>
                        <p>Check-Out: <?= $attendance['time_out'] ?? '<span class="text-muted">Not marked</span>' ?></p>
                        <form method="post" class="d-flex justify-content-center gap-3">
                          <?php if (!$attendance): ?>
                            <button name="action" value="checkin" class="btn btn-success">✅ Check In</button>
                          <?php elseif (!$attendance['time_out']): ?>
                            <button name="action" value="checkout" class="btn btn-danger">🚪 Check Out</button>
                          <?php else: ?>
                            <button class="btn btn-secondary" disabled>✔️ Attendance Complete</button>
                          <?php endif; ?>
                        </form>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- Leave Summary -->
                <div class="accordion-item">
                  <h2 class="accordion-header" id="headingLeave">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseLeave">
                      📝 Leave Summary
                    </button>
                  </h2>
                  <div id="collapseLeave" class="accordion-collapse collapse">
                    <div class="accordion-body">
                      <?php if ($leaveBalance): ?>
                        <ul class="list-group">
                          <li class="list-group-item">Annual: <?= $leaveBalance['annual_leave'] - $leaveBalance['used_annual'] ?> / <?= $leaveBalance['annual_leave'] ?></li>
                          <li class="list-group-item">Medical: <?= $leaveBalance['medical_leave'] - $leaveBalance['used_medical'] ?> / <?= $leaveBalance['medical_leave'] ?></li>
                          <li class="list-group-item">Hospital: <?= $leaveBalance['hospital_leave'] - $leaveBalance['used_hospital'] ?> / <?= $leaveBalance['hospital_leave'] ?></li>
                          <li class="list-group-item">Unpaid: <?= $leaveBalance['unpaid_leave'] - $leaveBalance['used_unpaid'] ?> / <?= $leaveBalance['unpaid_leave'] ?></li>
                        </ul>
                      <?php else: ?>
                        <p class="text-muted">Leave balance not assigned.</p>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>

                <!-- Payslip -->
                <div class="accordion-item">
                  <h2 class="accordion-header" id="headingPayslip">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapsePayslip">
                      💰 Payslip
                    </button>
                  </h2>
                  <div id="collapsePayslip" class="accordion-collapse collapse">
                    <div class="accordion-body text-center">
                      <?php if ($latestPayslip): ?>
                        <p><?= $latestPayslip['month'] ?></p>
                        <a href="../uploads/payslips/<?= $latestPayslip['file_path'] ?>" target="_blank" class="btn btn-outline-dark btn-sm">📄 View PDF</a>
                      <?php else: ?>
                        <p class="text-muted">No payslip available</p>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>

                <!-- KET -->
                <div class="accordion-item">
                  <h2 class="accordion-header" id="headingKET">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseKET">
                      📄 Employment Terms
                    </button>
                  </h2>
                  <div id="collapseKET" class="accordion-collapse collapse">
                    <div class="accordion-body text-center">
                      <?php if ($latestKET): ?>
                        <p><strong><?= $latestKET['position'] ?></strong></p>
                        <p><?= $latestKET['start_date'] ?> - <?= $latestKET['end_date'] ?></p>
                        <a href="../uploads/kets/<?= $latestKET['contract_file'] ?>" target="_blank" class="btn btn-outline-info btn-sm">📄 View Contract</a>
                      <?php else: ?>
                        <p class="text-muted">No KET available</p>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>

                <!-- Dashboard Links -->
                <div class="accordion-item">
                  <h2 class="accordion-header" id="headingLinks">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseLinks">
                      📂 Quick Links
                    </button>
                  </h2>
                  <div id="collapseLinks" class="accordion-collapse collapse">
                    <div class="accordion-body">
                      <div class="row g-3">
                        <?php
                          $tiles = [
                            ['view_roster.php', '📋', 'View Roster'],
                            ['attendance_summary.php', '📝', 'Attendance Summary'],
                            ['leave_apply.php', '📝', 'Leave Apply'],
                            ['view_leave.php', '📝', 'Leave History'],
                            ['view_payslip.php', '💰', 'View Payslip'],
                            ['view_employment_term.php', '📄', 'Employment Terms'],
                            ['report_incident.php', '🚨', 'Report Incident'],
                            ['view_incidents.php', '📁', 'My Incidents'],
                          ];
                          foreach ($tiles as [$href, $icon, $text]) {
                            echo <<<HTML
                            <div class="col-6 col-md-3">
                              <a href="$href" class="text-decoration-none">
                                <div class="text-center border rounded p-3 bg-white shadow-sm h-100">
                                  <div class="fs-2">$icon</div>
                                  <div class="small mt-1">$text</div>
                                </div>
                              </a>
                            </div>
                            HTML;
                          }
                        ?>
                      </div>
                    </div>
                  </div>
                </div>
          </div>
      </div>
      <div>
  </div>
</div>


    <!-- Toast -->
    <?php if ($toastMessage): ?>
    <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 9999">
      <div class="toast show text-white bg-success">
        <div class="toast-body">
          <?= $toastMessage ?>
        </div>
      </div>
    </div>
    <?php endif; ?>

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