<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user = requireRole([1, 5]);
$db   = getDB();
$id   = (int)post('id', 0);
if (!$id) apiError('Employee ID required.', 422);

$stmt = $db->prepare("
    SELECT e.*, u.full_name AS created_by_name,
           lu.id AS linked_user_id, lu.username AS linked_username, lu.full_name AS linked_user_name
    FROM employees e
    LEFT JOIN users u  ON u.id  = e.created_by
    LEFT JOIN users lu ON lu.id = e.user_id
    WHERE e.id = ?
");
$stmt->execute([$id]);
$emp = $stmt->fetch();
if (!$emp) apiError('Employee not found.', 404);

// Salary history
$s = $db->prepare("SELECT * FROM employee_salaries WHERE employee_id=? ORDER BY effective_date DESC");
$s->execute([$id]); $emp['salaries'] = $s->fetchAll();

// Allowances & Deductions
$a = $db->prepare("SELECT * FROM employee_allowances WHERE employee_id=? AND is_active=1");
$a->execute([$id]); $emp['allowances'] = $a->fetchAll();
$d = $db->prepare("SELECT * FROM employee_deductions WHERE employee_id=? AND is_active=1");
$d->execute([$id]); $emp['deductions'] = $d->fetchAll();

// Leave balance for current year
$lb = $db->prepare("SELECT * FROM employee_leave_balance WHERE employee_id=? AND year=YEAR(CURDATE()) ORDER BY leave_type");
$lb->execute([$id]); $emp['leave_balances'] = $lb->fetchAll();

// Recent leave
$rl = $db->prepare("SELECT * FROM employee_leave WHERE employee_id=? ORDER BY created_at DESC LIMIT 10");
$rl->execute([$id]); $emp['recent_leave'] = $rl->fetchAll();

// Documents
$ed = $db->prepare("SELECT ed.*, u.full_name AS uploaded_by_name FROM employee_documents ed LEFT JOIN users u ON u.id=ed.uploaded_by WHERE ed.employee_id=? ORDER BY ed.created_at DESC");
$ed->execute([$id]); $emp['documents'] = $ed->fetchAll();

// Warnings
$ew = $db->prepare("SELECT ew.*, u.full_name AS issued_by_name FROM employee_warnings ew LEFT JOIN users u ON u.id=ew.issued_by WHERE ew.employee_id=? ORDER BY ew.date_issued DESC");
$ew->execute([$id]); $emp['warnings'] = $ew->fetchAll();

apiSuccess(['employee' => $emp]);
