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

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

// Handle upload
$success = $error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload'])) {
  $officer_id = $_POST['officer_id'];
  $month = $_POST['month'];

  if ($_FILES['payslip']['error'] === 0 && $_FILES['payslip']['type'] === 'application/pdf') {
    $filename = time() . "_" . basename($_FILES['payslip']['name']);
    $targetPath = "../uploads/payslips/" . $filename;

    if (move_uploaded_file($_FILES['payslip']['tmp_name'], $targetPath)) {
      $stmt = $pdo->prepare("INSERT INTO payslips (officer_id, month, file_path) VALUES (?, ?, ?)");
      $stmt->execute([$officer_id, $month, $filename]);
      $success = "Payslip uploaded successfully.";
    } else {
      $error = "Failed to move uploaded file.";
    }
  } else {
    $error = "Only PDF files are allowed.";
  }
}

// Handle delete
if (isset($_GET['delete'])) {
  $id = $_GET['delete'];
  $stmt = $pdo->prepare("SELECT file_path FROM payslips WHERE id = ?");
  $stmt->execute([$id]);
  $file = $stmt->fetchColumn();
  if ($file) {
    @unlink("../uploads/payslips/$file");
    $pdo->prepare("DELETE FROM payslips WHERE id = ?")->execute([$id]);
    $success = "Payslip deleted.";
  }
}

// Handle update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_id'])) {
  $stmt = $pdo->prepare("UPDATE payslips SET month = ? WHERE id = ?");
  $stmt->execute([$_POST['edit_month'], $_POST['edit_id']]);
  $success = "Payslip updated.";
}

$officers = $pdo->query("SELECT id, username FROM users WHERE role = 'officer' ORDER BY username ASC")->fetchAll();
$payslips = $pdo->query("SELECT p.*, u.username FROM payslips p JOIN users u ON p.officer_id = u.id ORDER BY p.id DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Upload Payslip | CFS System OS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- AdminLTE & Bootstrap -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  
  <style>
    .form-section { background: #fff; padding: 25px; border-radius: 8px; box-shadow: 0 0 6px rgba(0,0,0,0.05); }
  </style>
</head>
<body>

<?php include '../includes/topbar.php'; ?>
<?php include '../includes/sidebar.php'; ?>

<div class="main-content" id="mainContent">
  <div class="container mt-4">

    <h4 class="mb-3"><i class="fas fa-file-upload"></i> Upload Payslip (PDF)</h4>
    <div class="form-section mb-4">

      <?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>
      <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>

      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="upload" value="1">
        <div class="mb-3">
          <label>Officer</label>
          <select name="officer_id" class="form-select" required>
            <option value="">-- Select Officer --</option>
            <?php foreach ($officers as $o): ?>
              <option value="<?= $o['id'] ?>"><?= htmlspecialchars($o['username']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="mb-3">
          <label>Month</label>
          <input type="text" name="month" class="form-control" placeholder="e.g. March 2025" required>
        </div>

        <div class="mb-3">
          <label>Payslip PDF</label>
          <input type="file" name="payslip" accept="application/pdf" class="form-control" required>
        </div>

        <button class="btn btn-primary"><i class="fas fa-upload"></i> Upload</button>
      </form>
    </div>

    <!-- Payslips Table -->
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fas fa-list"></i> Uploaded Payslips</h5>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table id="payslipTable" class="table table-striped">
            <thead>
              <tr>
                <th>#</th>
                <th>Officer</th>
                <th>Month</th>
                <th>View</th>
                <th>Edit</th>
                <th>Delete</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($payslips as $index => $p): ?>
                <tr>
                  <td><?= $index + 1 ?></td>
                  <td><?= htmlspecialchars($p['username']) ?></td>
                  <td><?= htmlspecialchars($p['month']) ?></td>
                  <td><a href="../uploads/payslips/<?= $p['file_path'] ?>" target="_blank" class="btn btn-info btn-sm"><i class="fas fa-eye"></i></a></td>
                  <td>
                    <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editModal<?= $p['id'] ?>"><i class="fas fa-edit"></i></button>

                    <!-- Edit Modal -->
                    <div class="modal fade" id="editModal<?= $p['id'] ?>" tabindex="-1">
                      <div class="modal-dialog">
                        <form method="post" class="modal-content">
                          <input type="hidden" name="edit_id" value="<?= $p['id'] ?>">
                          <div class="modal-header"><h5 class="modal-title">Edit Month</h5></div>
                          <div class="modal-body">
                            <input type="text" name="edit_month" class="form-control" value="<?= htmlspecialchars($p['month']) ?>" required>
                          </div>
                          <div class="modal-footer">
                            <button class="btn btn-primary">Save</button>
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                          </div>
                        </form>
                      </div>
                    </div>
                  </td>
                  <td>
                    <a href="?delete=<?= $p['id'] ?>" onclick="return confirm('Delete this payslip?')" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i></a>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

  </div>
</div>

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
<script>
  $(document).ready(function () {
    $('#payslipTable').DataTable();
  });
</script>
</body>
</html>
