<?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'); 

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

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

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

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

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

// Handle check-in/out
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if ($_POST['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 ($_POST['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;
  }
}

$toastMessage = '';
if (isset($_GET['checkin'])) $toastMessage = "✅ Check-In Successful!";
if (isset($_GET['checkout'])) $toastMessage = "✅ Check-Out Successful!";
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Officer Dashboard | CFS System OS</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet" />
  <style>
    body { background-color:rgb(13, 107, 248); font-family: 'Segoe UI', sans-serif; }
    .card-box {
      border-radius: 15px;
      padding: 25px;
      background: #fff;
      box-shadow: 0 4px 16px rgba(0,0,0,0.06);
      transition: all 0.2s ease-in-out;
    }
    .card-box:hover { transform: translateY(-4px); }
    .toast-container {
      position: fixed;
      top: 1rem;
      right: 1rem;
      z-index: 1055;
    }
    .table th, .table td {
      vertical-align: middle;
    }
  </style>
</head>
<body>

<!-- Topbar -->
<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>

<div class="container">
  <div class="row g-4">
    <!-- Attendance -->
    <div class="col-md-6">
      <div class="card-box text-center">
        <h5 class="text-primary mb-3">🕒 Attendance - <?= $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 && !$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>
<!-- Manage Leave ------------------------------------------------------->
    <!-- Leave Summary -->
    <div class="col-md-6">
      <div class="card-box text-center">
        <h5 class="text-success mb-3">📝 Latest Leave</h5>
        <?php if ($leaveBalance): ?>
        <ul class="list-group small">
          <li class="list-group-item">Annual Leave: <?= $leaveBalance['annual_leave'] - $leaveBalance['used_annual'] ?> / <?= $leaveBalance['annual_leave'] ?></li>
          <li class="list-group-item">Medical Leave: <?= $leaveBalance['medical_leave'] - $leaveBalance['used_medical'] ?> / <?= $leaveBalance['medical_leave'] ?></li>
          <li class="list-group-item">Hospital Leave: <?= $leaveBalance['hospital_leave'] - $leaveBalance['used_hospital'] ?> / <?= $leaveBalance['hospital_leave'] ?></li>
          <li class="list-group-item">Unpaid Leave: <?= $leaveBalance['unpaid_leave'] - $leaveBalance['used_unpaid'] ?> / <?= $leaveBalance['unpaid_leave'] ?></li>
        </ul>
        <?php else: ?>
        <p class="text-muted">Leave balance not assigned yet.</p>
        <?php endif; ?>
      </div>
    </div>

    <!-- Leave Application Form -->
    <div class="col-md-6">
      <div class="card-box">
        <h5 class="text-success mb-3">📤 Apply for Leave</h5>
        <form method="post" action="leave_submit.php">
          <div class="mb-2">
            <select name="leave_type" class="form-select" required>
              <option value="">Select Leave Type</option>
              <option value="annual">Annual</option>
              <option value="medical">Medical</option>
              <option value="hospital">Hospital</option>
              <option value="unpaid">Unpaid</option>
            </select>
          </div>
          <div class="row mb-2">
            <div class="col">
              <input type="date" name="start_date" class="form-control" required>
            </div>
            <div class="col">
              <input type="date" name="end_date" class="form-control" required>
            </div>
          </div>
          <div class="mb-2">
            <input type="text" name="reason" class="form-control" placeholder="Reason" required>
          </div>
          <button class="btn btn-outline-primary btn-sm w-100">Submit Request</button>
        </form>
      </div>
    </div>

    <!-- Leave History -->
    <div class="col-md-12">
      <div class="card-box">
        <h6 class="mb-3 text-secondary">📄 Recent Leave History</h6>
        <table class="table table-bordered table-striped small">
          <thead>
            <tr>
              <th>Type</th>
              <th>Start</th>
              <th>End</th>
              <th>Reason</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($recentLeaves as $l): ?>
            <tr>
              <td><?= ucfirst($l['leave_type']) ?></td>
              <td><?= $l['start_date'] ?></td>
              <td><?= $l['end_date'] ?></td>
              <td><?= htmlspecialchars($l['reason']) ?></td>
              <td>
                <span class="badge bg-<?= $l['status'] === 'approved' ? 'success' : ($l['status'] === 'rejected' ? 'danger' : 'warning') ?>">
                  <?= ucfirst($l['status']) ?>
                </span>
              </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($recentLeaves)): ?>
              <tr><td colspan="5" class="text-center text-muted">No leave requests yet.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>  

<!------------------------------------------------------------------------>
    <!-- Payslip -->
    <div class="col-md-6">
      <div class="card-box text-center">
        <h5 class="text-dark mb-3">💼 Latest Payslip</h5>
        <?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>

    <!-- KET -->
    <div class="col-md-6">
      <div class="card-box text-center">
        <h5 class="text-info mb-3">📑 Employment Terms (KET)</h5>
        <?php if ($latestKET): ?>
          <p>Position: <strong><?= $latestKET['position'] ?></strong></p>
          <p><?= $latestKET['start_date'] ?> to <?= $latestKET['end_date'] ?></p>
          <?php if ($latestKET['contract_file']): ?>
            <a href="../uploads/kets/<?= $latestKET['contract_file'] ?>" target="_blank" class="btn btn-outline-info btn-sm">View Contract</a>
          <?php endif; ?>
        <?php else: ?>
          <p class="text-muted">No KET available</p>
        <?php endif; ?>
      </div>
    </div>

    <!-- Incident Reporting -->
    <div class="col-md-12">
        <div class="card-box">
            <h5 class="mb-3 text-danger">🚨 Submit Incident Report</h5>
            <form method="POST" action="submit_incident.php" enctype="multipart/form-data">
            <div class="mb-3">
                <label class="form-label">Incident Title</label>
                <input type="text" name="title" class="form-control" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Description</label>
                <textarea name="description" class="form-control" rows="4" required></textarea>
            </div>
            <div class="mb-3">
                <label class="form-label">Photo (optional)</label>
                <input type="file" name="photo" accept="image/*" class="form-control">
            </div>
            <div class="mb-3">
                <label class="form-label">Video (optional)</label>
                <input type="file" name="video" accept="video/*" class="form-control">
            </div>
            <button class="btn btn-danger" type="submit">Submit Incident</button>
            </form>
        </div>
    </div>

  </div>
</div>

<!-- Toast -->
<?php if ($toastMessage): ?>
<div class="toast-container">
  <div class="toast align-items-center text-bg-success border-0 show">
    <div class="d-flex">
      <div class="toast-body"><?= $toastMessage ?></div>
      <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
    </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>
