<?php

require_once __DIR__ . '/includes/settings_helpers.php';

settings_require_auth();
settings_ensure_tables($conn);

$org = settings_get_current_org($conn);
$orgId = (int) ($org['id'] ?? 0);
$flash = settings_flash_message();
$errors = [];

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $stmt = $conn->prepare(
        "SELECT d.name,
         (SELECT COUNT(*) FROM employees e WHERE e.designation = d.name AND e.is_deleted = 0) AS employees
         FROM designations d
         WHERE d.organization_id = ?
         ORDER BY d.id DESC"
    );
    if ($stmt) {
        $stmt->bind_param('i', $orgId);
        $stmt->execute();
        $result = $stmt->get_result();
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="designations.csv"');
        $out = fopen('php://output', 'w');
        fputcsv($out, ['Designation Name', 'Total Employees']);
        while ($row = $result->fetch_assoc()) {
            fputcsv($out, [$row['name'], $row['employees']]);
        }
        fclose($out);
        $stmt->close();
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['designation_action'] ?? '';

    if ($action === 'create') {
        $name = trim((string) ($_POST['designation_name'] ?? ''));
        if ($name === '') {
            $errors[] = 'Designation name is required.';
        }

        if (!$errors) {
            $stmt = $conn->prepare("INSERT INTO designations (organization_id, name) VALUES (?, ?)");
            if ($stmt) {
                $stmt->bind_param('is', $orgId, $name);
                if ($stmt->execute()) {
                    settings_set_flash('success', 'Designation saved successfully.');
                    $stmt->close();
                    header('Location: designations.php');
                    exit();
                }
                $errors[] = 'Unable to save designation. It may already exist.';
                $stmt->close();
            }
        }
    } elseif ($action === 'delete') {
        $designationId = (int) ($_POST['designation_id'] ?? 0);
        if ($designationId > 0) {
            $stmt = $conn->prepare("DELETE FROM designations WHERE id = ? AND organization_id = ?");
            if ($stmt) {
                $stmt->bind_param('ii', $designationId, $orgId);
                $stmt->execute();
                $stmt->close();
                settings_set_flash('success', 'Designation deleted successfully.');
                header('Location: designations.php');
                exit();
            }
        }
    }
}

$designations = [];
$stmt = $conn->prepare(
    "SELECT d.id, d.name,
     (SELECT COUNT(*) FROM employees e WHERE e.designation = d.name AND e.is_deleted = 0) AS employees
     FROM designations d
     WHERE d.organization_id = ?
     ORDER BY d.id DESC"
);
if ($stmt) {
    $stmt->bind_param('i', $orgId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $designations[] = $row;
    }
    $stmt->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Designations | Settings</title>
  <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
  <link rel="stylesheet" href="assets/font-inter.css">
  <link rel="stylesheet" href="orgprofile.css">
  <link rel="stylesheet" href="departments.css">
</head>
<body class="orgprofile-page">
  <?php settings_render_header($_SESSION['org_name'] ?? 'demo', 'dashboard.php', 'fa-id-badge'); ?>

  <main class="profile-layout">
    <?php settings_render_sidebar('designations'); ?>

    <section class="profile-main">
      <div class="profile-head dept-toolbar">
        <h1>Designations</h1>
        <div class="toolbar-actions">
          <a class="btn-export" href="designations.php?export=csv" title="Export"><i class="fa-solid fa-download"></i></a>
          <button class="btn-new" type="button" onclick="openModal()"><i class="fa-solid fa-plus"></i> New Designation</button>
        </div>
      </div>

      <div class="profile-card dept-card">
        <?php if (!empty($flash['message'])): ?>
          <div class="alert-ok"><?php echo htmlspecialchars($flash['message']); ?></div>
        <?php endif; ?>

        <?php if ($errors): ?>
          <div class="alert-err">
            <div class="alert-err-title">Please fix the following:</div>
            <ul>
              <?php foreach ($errors as $error): ?>
                <li><?php echo htmlspecialchars($error); ?></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endif; ?>

        <?php if ($designations): ?>
          <table class="dept-table">
            <thead>
              <tr>
                <th>Designation Name</th>
                <th>Total Employees</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($designations as $designation): ?>
                <tr>
                  <td><a class="dept-name-link" href="#"><?php echo htmlspecialchars($designation['name']); ?></a></td>
                  <td><span class="badge-count"><?php echo (int) $designation['employees']; ?></span></td>
                  <td>
                    <div class="row-actions row-actions--visible">
                      <form method="POST" class="inline-form" onsubmit="return confirm('Delete this designation?');">
                        <input type="hidden" name="designation_action" value="delete">
                        <input type="hidden" name="designation_id" value="<?php echo (int) $designation['id']; ?>">
                        <button class="row-btn danger" type="submit" title="Delete"><i class="fa-solid fa-trash"></i></button>
                      </form>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        <?php else: ?>
          <div class="empty-state">
            <i class="fa-solid fa-id-badge"></i>
            <p>No designations added yet.</p>
            <button class="btn-new" type="button" onclick="openModal()"><i class="fa-solid fa-plus"></i> New Designation</button>
          </div>
        <?php endif; ?>
      </div>
    </section>
  </main>

  <div class="modal-overlay" id="designationModal">
    <div class="modal">
      <h3>New Designation</h3>
      <form method="POST">
        <input type="hidden" name="designation_action" value="create">
        <div class="field-group">
          <label>Designation Name<span class="req">*</span></label>
          <input class="modal-input" type="text" name="designation_name" required>
        </div>
        <div class="modal-footer">
          <button class="btn-cancel" type="button" onclick="closeModal()">Cancel</button>
          <button class="save-btn" type="submit">Save</button>
        </div>
      </form>
    </div>
  </div>

  <script>
    function openModal() { document.getElementById('designationModal').classList.add('open'); }
    function closeModal() { document.getElementById('designationModal').classList.remove('open'); }
    document.getElementById('designationModal').addEventListener('click', function (event) {
      if (event.target === this) {
        closeModal();
      }
    });
  </script>
</body>
</html>
