<?php
// POST /api/employees/leave_apply.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireAuth();
$db   = getDB();

$employeeId = (int)post('employee_id', 0);
$startDate  = trim(post('start_date', ''));
$endDate    = trim(post('end_date', ''));
$days       = (float)post('days', 0);
$leaveType  = post('leave_type', 'annual');
$reason     = post('reason', '');

if (!$employeeId) apiError('Employee ID required.', 422);
if (!$startDate || !$endDate) apiError('Start and end date required.', 422);
if ($days <= 0) apiError('Days must be greater than 0.', 422);

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

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