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

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

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

$username = $_SESSION['username'] ?? 'User';
$userRole = strtolower(trim($_SESSION['role'] ?? ''));

if (!in_array($userRole, ['admin', 'superadmin','hr'])) {
    die("Access Denied");
}

// Filters & Pagination Config
$search = trim($_GET['search'] ?? '');
$departmentFilter = intval($_GET['department'] ?? 0);
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 10;
$offset = ($page - 1) * $perPage;

// Fetch Departments Dropdown Data
$departments = [];
$res = $conn->query("SELECT id, name FROM departments ORDER BY name");
if ($res) {
    while ($row = $res->fetch_assoc()) {
        $departments[$row['id']] = $row['name'];
    }
}

// Statistics Aggregation
$totalEmployees = $conn->query("SELECT COUNT(*) total FROM employees")->fetch_assoc()['total'] ?? 0;
$totalManagers  = $conn->query("SELECT COUNT(*) total FROM employees WHERE is_manager=1")->fetch_assoc()['total'] ?? 0;
$totalDepartments = $conn->query("SELECT COUNT(*) total FROM departments")->fetch_assoc()['total'] ?? 0;
$newHires       = $conn->query("SELECT COUNT(*) total FROM employees WHERE MONTH(date_hired)=MONTH(CURDATE()) AND YEAR(date_hired)=YEAR(CURDATE())")->fetch_assoc()['total'] ?? 0;

// Build Dynamic SQL Conditions
$where = [];
$params = [];
$types = '';

if ($search != '') {
    $where[] = "(e.name LIKE ? OR e.employee_no LIKE ? OR e.email LIKE ? OR e.phone LIKE ? OR e.designation LIKE ? OR e.position LIKE ?)";
    $keyword = "%$search%";
    array_push($params, $keyword, $keyword, $keyword, $keyword, $keyword, $keyword);
    $types .= "ssssss";
}

if ($departmentFilter) {
    $where[] = "e.department_id = ?";
    $params[] = $departmentFilter;
    $types .= "i";
}

$whereSql = count($where) ? 'WHERE ' . implode(" AND ", $where) : '';

// Count Total Rows for Pagination
$countSql = "SELECT COUNT(*) total FROM employees e LEFT JOIN departments d ON d.id=e.department_id $whereSql";
$stmt = $conn->prepare($countSql);
if ($types) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$totalRows = $stmt->get_result()->fetch_assoc()['total'] ?? 0;
$totalPages = max(1, ceil($totalRows / $perPage));

// Fetch Records
$sql = "SELECT e.*, d.name as department FROM employees e LEFT JOIN departments d ON d.id=e.department_id $whereSql ORDER BY e.name LIMIT ?, ?";
$stmt = $conn->prepare($sql);

if ($types) {
    $bindTypes = $types . "ii";
    $bindValues = array_merge($params, [$offset, $perPage]);
    $stmt->bind_param($bindTypes, ...$bindValues);
} else {
    $stmt->bind_param("ii", $offset, $perPage);
}
$stmt->execute();
$employeesResult = $stmt->get_result();

// Data Formatting Array for View
$employees = [];
while ($row = $employeesResult->fetch_assoc()) {
    $cleanName = !empty($row['name']) ? htmlspecialchars($row['name']) : 'Unnamed Staff';
    
    // Parse Initials cleanly
    $cleanStr = preg_replace('/^(mr\.|ms\.|mrs\.|dr\.|prof\.)\s+/i', '', trim($cleanName));
    $words = explode(' ', $cleanStr);
    $initials = strtoupper(substr(($words[0] ?? '') . ($words[1] ?? ''), 0, 2));
    if(empty($initials)) $initials = 'EE';

    // Map avatar field (checking both 'avater' and 'avatar' column spellings)
    $avaterPath = $row['avater'] ?? $row['avatar'] ?? '';

    $employees[] = [
        'id'          => $row['id'],
        'name'        => $cleanName,
        'avater'      => $avaterPath,
        'avatar'      => $avaterPath,
        'email'       => !empty($row['email']) ? htmlspecialchars($row['email']) : 'no-email@system.local',
        'employee_no' => !empty($row['employee_no']) ? htmlspecialchars($row['employee_no']) : 'EMP----',
        'department'  => !empty($row['department']) ? htmlspecialchars($row['department']) : 'Unassigned',
        'designation' => !empty($row['designation']) ? htmlspecialchars($row['designation']) : 'Staff Force',
        'position'    => !empty($row['position']) ? htmlspecialchars($row['position']) : 'Generalist',
        'date_hired'  => !empty($row['date_hired']) ? date('Y-m-d', strtotime($row['date_hired'])) : '---',
        'initials'    => $initials
    ];
}