<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user   = requireAuth();
$db     = getDB();
$empId  = (int)post('employee_id', 0);
$year   = (int)post('year', date('Y'));

// Employees can see their own, HR/Admin can see anyone
if (!$empId) {
    $empStmt = $db->prepare("SELECT id FROM employees WHERE user_id = ?");
    $empStmt->execute([$user['id']]);
    $emp = $empStmt->fetch();
    $empId = $emp ? (int)$emp['id'] : 0;
}
if (!$empId) apiError('Employee not found.', 404);
if (!in_array($user['role_id'], [1,5])) {
    $empStmt = $db->prepare("SELECT id FROM employees WHERE user_id=? AND id=?");
    $empStmt->execute([$user['id'], $empId]);
    if (!$empStmt->fetch()) apiError('Access denied.', 403);
}

$stmt = $db->prepare("SELECT * FROM employee_leave_balance WHERE employee_id=? AND year=?");
$stmt->execute([$empId, $year]);
$balances = $stmt->fetchAll();

// Also get pending leave days
$pendStmt = $db->prepare("SELECT leave_type, SUM(days) AS pending_days FROM employee_leave WHERE employee_id=? AND status='pending' AND YEAR(start_date)=? GROUP BY leave_type");
$pendStmt->execute([$empId, $year]);
$pending = [];
foreach ($pendStmt->fetchAll() as $p) $pending[$p['leave_type']] = (float)$p['pending_days'];

apiSuccess(['balances' => $balances, 'pending' => $pending]);
