<?php
// Employee self-service leave application
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user   = requireAuth();
$db     = getDB();

// Get employee linked to this user
$empStmt = $db->prepare("SELECT id FROM employees WHERE user_id = ?");
$empStmt->execute([$user['id']]);
$emp = $empStmt->fetch();
if (!$emp) apiError('No employee profile linked to your account. Contact HR.', 403);

$empId     = $emp['id'];
$startDate = post('start_date', '');
$endDate   = post('end_date', $startDate);
$leaveType = post('leave_type', 'annual');
$reason    = post('reason', '');
$days      = (float)post('days', 0);

if (!$startDate) apiError('Start date required.', 422);
if ($days <= 0) {
    // Auto-calculate weekdays
    $d1 = new DateTime($startDate);
    $d2 = new DateTime($endDate);
    $days = 0;
    for ($d = clone $d1; $d <= $d2; $d->modify('+1 day')) {
        $dow = (int)$d->format('N');
        if ($dow < 6) $days++;
    }
}

// Check available balance
$balStmt = $db->prepare("SELECT allocated, used, carried_over FROM employee_leave_balance WHERE employee_id=? AND year=YEAR(?) AND leave_type=?");
$balStmt->execute([$empId, $startDate, $leaveType]);
$bal = $balStmt->fetch();
$available = $bal ? (float)$bal['allocated'] + (float)$bal['carried_over'] - (float)$bal['used'] : 0;

if (in_array($leaveType, ['annual','sick','family']) && $available < $days) {
    apiError("Insufficient leave balance. Available: $available days, Requested: $days days.", 422);
}

$db->prepare("INSERT INTO employee_leave (employee_id, user_id, leave_type, start_date, end_date, days, reason, status) VALUES (?,?,?,?,?,?,?,'pending')")
   ->execute([$empId, $user['id'], $leaveType, $startDate, $endDate, $days, $reason]);

apiSuccess(['id' => (int)$db->lastInsertId(), 'days' => $days], 'Leave application submitted.', 201);
