<?php
// departments_controller.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
session_write_close();

date_default_timezone_set('Africa/Lagos');
require '../config.php';

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

$username = $_SESSION['username'] ?? 'User';
$role = strtolower(trim($_SESSION['role'] ?? 'staff'));
$isAdmin = in_array($role, ['admin', 'superadmin']);

$successMessage = '';
$errorMessage = '';

// Check URL parameters for redirection status messages
if (isset($_GET['saved'])) $successMessage = "Department vector initialized and saved.";
if (isset($_GET['updated'])) $successMessage = "Structural properties successfully saved.";
if (isset($_GET['deleted'])) $successMessage = "Target department successfully dropped from roster records.";
if (isset($_GET['error']) && $_GET['error'] === 'in_use') {
    $errorMessage = "Cannot drop module: Active personnel allocations are mapped to this department baseline.";
}

// Handle Single Row Query for inline Edit Mode
$editData = null;
if (isset($_GET['edit_id']) && $isAdmin) {
    $editId = intval($_GET['edit_id']);
    $stmt = $conn->prepare("SELECT * FROM departments WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $editId);
    $stmt->execute();
    $editData = $stmt->get_result()->fetch_assoc();
}

// Statistics Aggregation Engine
$totalDepts = 0;
$totalStaffMapped = 0;

$countDeptsRes = $conn->query("SELECT COUNT(*) as total FROM departments");
if ($countDeptsRes) $totalDepts = $countDeptsRes->fetch_assoc()['total'];

$countStaffRes = $conn->query("SELECT COUNT(*) as total FROM employees WHERE department_id IS NOT NULL AND department_id > 0");
if ($countStaffRes) $totalStaffMapped = $countStaffRes->fetch_assoc()['total'];

// LOAD ALL DEPARTMENTS WITH AGGREGATED HEADCOUNT METRICS
$departments = [];
$sql = "SELECT d.*, COUNT(e.id) as headcount 
        FROM departments d 
        LEFT JOIN employees e ON e.department_id = d.id 
        GROUP BY d.id 
        ORDER BY d.name";
$res = $conn->query($sql);
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $departments[] = [
            'id' => $row['id'],
            'name' => htmlspecialchars($row['name']),
            'code' => !empty($row['code']) ? htmlspecialchars($row['code']) : '—',
            'headcount' => intval($row['headcount'])
        ];
    }
}