<?php

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

settings_require_auth();
settings_ensure_tables($conn);

$org = settings_get_current_org($conn);
$orgId = (string) ($_SESSION['org_id'] ?? ($org['id'] ?? ''));
$flash = settings_flash_message();
$errors = [];

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

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

    if ($action === 'create') {
        $name = trim((string) ($_POST['dept_name'] ?? ''));
        $code = trim((string) ($_POST['dept_code'] ?? ''));
        $desc = trim((string) ($_POST['dept_desc'] ?? ''));

        if ($name === '') {
            $errors[] = 'Department name is required.';
        }

        if (!$errors) {
            $stmt = $conn->prepare(
                "INSERT INTO departments (org_id, name, code, description)
                 VALUES (?, ?, ?, ?)"
            );
            if ($stmt) {
                $stmt->bind_param('ssss', $orgId, $name, $code, $desc);
                if ($stmt->execute()) {
                    settings_set_flash('success', 'Department saved successfully.');
                    $stmt->close();
                    header('Location: departments.php');
                    exit();
                }
                $errors[] = 'Unable to save department.';
                $stmt->close();
            }
        }
    } elseif ($action === 'delete') {
        $deleteId = (int) ($_POST['dept_id'] ?? 0);
        if ($deleteId > 0) {
            $stmt = $conn->prepare("DELETE FROM departments WHERE id = ? AND org_id = ?");
            if ($stmt) {
                $stmt->bind_param('is', $deleteId, $orgId);
                $stmt->execute();
                $stmt->close();
                settings_set_flash('success', 'Department deleted successfully.');
                header('Location: departments.php');
                exit();
            }
        }
    }
}

$departments = [];
$stmt = $conn->prepare(
    "SELECT d.id, d.name, d.code, d.description,
     (SELECT COUNT(*) FROM employees e WHERE e.department = d.name AND e.is_deleted = 0) AS employees
     FROM departments d
     WHERE d.org_id = ?
     ORDER BY d.id DESC"
);
if ($stmt) {
    $stmt->bind_param('s', $orgId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $departments[] = $row;
    }
    $stmt->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
  <title>Departments | 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-building'); ?>

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

    <section class="profile-main">
      <div class="profile-head dept-toolbar">
        <h1>Departments</h1>
        <div class="toolbar-actions">
          <a class="btn-export" href="departments.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 Department</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 ($departments): ?>
          <table class="dept-table">
            <thead>
              <tr>
                <th>Department Name</th>
                <th>Department Code</th>
                <th>Description</th>
                <th>Total Employees</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($departments as $dept): ?>
                <tr>
                  <td><a class="dept-name-link" href="#"><?php echo htmlspecialchars($dept['name']); ?></a></td>
                  <td><?php echo htmlspecialchars($dept['code']); ?></td>
                  <td><?php echo htmlspecialchars($dept['description']); ?></td>
                  <td><span class="badge-count"><?php echo (int) $dept['employees']; ?></span></td>
                  <td>
                    <div class="row-actions row-actions--visible">
                      <form method="POST" class="inline-form" onsubmit="return confirm('Delete this department?');">
                        <input type="hidden" name="dept_action" value="delete">
                        <input type="hidden" name="dept_id" value="<?php echo (int) $dept['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-building"></i>
            <p>No departments added yet.</p>
            <button class="btn-new" type="button" onclick="openModal()"><i class="fa-solid fa-plus"></i> New Department</button>
          </div>
        <?php endif; ?>
      </div>
    </section>
  </main>

  <div class="modal-overlay" id="deptModal">
    <div class="modal">
      <h3>New Department</h3>
      <form method="POST">
        <input type="hidden" name="dept_action" value="create">
        <div class="field-group">
          <label>Department Name<span class="req">*</span></label>
          <input class="modal-input" type="text" name="dept_name" required>
        </div>
        <div class="field-group">
          <label>Department Code</label>
          <input class="modal-input" type="text" name="dept_code">
        </div>
        <div class="field-group">
          <label>Description</label>
          <textarea class="modal-input modal-textarea" name="dept_desc" rows="4" placeholder="Max 250 characters"></textarea>
        </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('deptModal').classList.add('open'); }
    function closeModal() { document.getElementById('deptModal').classList.remove('open'); }
    document.getElementById('deptModal').addEventListener('click', function (event) {
      if (event.target === this) {
        closeModal();
      }
    });
  </script>
</body>
</html>

