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

try {
    if ($action === 'list') {
        $stmt = $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");
        $stmt->execute([$empId]);
        apiSuccess(['warnings' => $stmt->fetchAll()]);
    }
    if ($action === 'delete') {
        $db->prepare("DELETE FROM employee_warnings WHERE id=? AND employee_id=?")->execute([(int)post('id'), $empId]);
        apiSuccess([], 'Deleted.');
    }
    if ($action === 'acknowledge') {
        $db->prepare("UPDATE employee_warnings SET acknowledged_at=NOW() WHERE id=? AND employee_id=?")->execute([(int)post('id'), $empId]);
        apiSuccess([], 'Acknowledged.');
    }
    // save
    $id = (int)post('id', 0);
    if ($id) {
        $db->prepare("UPDATE employee_warnings SET warning_type=?,date_issued=?,reason=?,outcome=?,follow_up_date=?,is_active=? WHERE id=? AND employee_id=?")
           ->execute([post('warning_type','verbal'), post('date_issued'), post('reason'), post('outcome'), post('follow_up_date') ?: null, post('is_active',1), $id, $empId]);
        apiSuccess(['id'=>$id], 'Updated.');
    } else {
        $db->prepare("INSERT INTO employee_warnings (employee_id,warning_type,date_issued,reason,outcome,follow_up_date,issued_by) VALUES (?,?,?,?,?,?,?)")
           ->execute([$empId, post('warning_type','verbal'), post('date_issued', date('Y-m-d')), post('reason'), post('outcome'), post('follow_up_date') ?: null, $user['id']]);
        apiSuccess(['id' => (int)$db->lastInsertId()], 'Warning recorded.');
    }
} catch (Exception $e) {
    apiError('Error: ' . $e->getMessage(), 500);
}
