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

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

// Leave
$leave = $pdo->prepare("SELECT * FROM leave_requests WHERE officer_id = ? ORDER BY id DESC LIMIT 1");
$leave->execute([$user_id]);
$latestLeave = $leave->fetch();

// 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: #f4f6f9; 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;
    }
  </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>

    <!-- Leave Summary -->
    <div class="col-md-6">
      <div class="card-box text-center">
        <h5 class="text-success mb-3">📝 Latest Leave</h5>
        <?php if ($latestLeave): ?>
          <p><strong><?= ucfirst($latestLeave['leave_type']) ?></strong> from <?= $latestLeave['start_date'] ?> to <?= $latestLeave['end_date'] ?></p>
          <span class="badge bg-<?= $latestLeave['status'] === 'approved' ? 'success' : ($latestLeave['status'] === 'rejected' ? 'danger' : 'warning') ?>">
            <?= ucfirst($latestLeave['status']) ?>
          </span>
        <?php else: ?>
          <p class="text-muted">No leave records</p>
        <?php endif; ?>
      </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>
