<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user   = requireRole([1, 5]);
$db     = getDB();
$action = post('action', '');
$empId  = (int)post('employee_id', 0);

if (!$empId) apiError('Employee ID required.', 422);

try {
    if ($action === 'list' || $action === '') {
        $stmt = $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");
        $stmt->execute([$empId]);
        apiSuccess(['documents' => $stmt->fetchAll()]);
    }

    if ($action === 'delete') {
        $id = (int)post('id');
        $stmt = $db->prepare("SELECT file_path FROM employee_documents WHERE id=? AND employee_id=?");
        $stmt->execute([$id, $empId]);
        $doc = $stmt->fetch();
        if ($doc && $doc['file_path'] && file_exists(__DIR__.'/../../'.$doc['file_path']))
            unlink(__DIR__.'/../../'.$doc['file_path']);
        $db->prepare("DELETE FROM employee_documents WHERE id=? AND employee_id=?")->execute([$id, $empId]);
        apiSuccess([], 'Deleted.');
    }

    if ($action !== 'upload') apiError('Unknown action.', 400);

    // upload/save
    $label    = post('label', 'Document');
    $docType  = post('doc_type', 'other');
    $expiry   = post('expiry_date') ?: null;
    $notes    = post('notes', '');

    $filePath = null; $filename = null; $origName = null;
    if (!empty($_FILES['document']) && $_FILES['document']['error'] === UPLOAD_ERR_OK) {
        $file  = $_FILES['document'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime  = finfo_file($finfo, $file['tmp_name']); finfo_close($finfo);
        $allowed = ['image/jpeg','image/png','image/webp','application/pdf'];
        if (!in_array($mime, $allowed)) apiError('Only images and PDFs allowed.', 422);
        if ($file['size'] > 20 * 1024 * 1024) apiError('Max 20MB.', 422);
        $dir = __DIR__ . '/../../uploads/employees/' . $empId . '/';
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        $ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)) ?: 'pdf';
        $filename = 'emp_' . uniqid() . '.' . $ext;
        if (!move_uploaded_file($file['tmp_name'], $dir . $filename)) apiError('Upload failed.', 500);
        $filePath = 'uploads/employees/' . $empId . '/' . $filename;
        $origName = $file['name'];
    }

    $db->prepare("INSERT INTO employee_documents (employee_id,doc_type,label,expiry_date,filename,file_path,original_name,notes,uploaded_by) VALUES (?,?,?,?,?,?,?,?,?)")
       ->execute([$empId, $docType, $label, $expiry, $filename, $filePath, $origName, $notes, $user['id']]);
    apiSuccess(['id' => (int)$db->lastInsertId()], 'Document saved.');
} catch (Exception $e) {
    apiError('Error: ' . $e->getMessage(), 500);
}
