<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user      = requireAuth();
$db        = getDB();
$action    = post('action','save');
$vehicleId = (int)post('vehicle_id',0);

try {
    if ($action === 'list') {
        if (!$vehicleId) apiError('Vehicle ID required.', 422);
        $stmt = $db->prepare("SELECT * FROM fleet_documents WHERE vehicle_id=? ORDER BY expiry_date");
        $stmt->execute([$vehicleId]);
        apiSuccess(['documents' => $stmt->fetchAll()]);
    }

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

    // save / upload
    if ($action === 'save') {
        if (!$vehicleId) apiError('Vehicle ID required.', 422);
        $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','image/gif','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/fleet/docs/' . $vehicleId . '/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)) ?: 'pdf';
            $filename = 'doc_' . uniqid() . '.' . $ext;
            if (!move_uploaded_file($file['tmp_name'], $dir . $filename)) apiError('Upload failed.', 500);
            $filePath = 'uploads/fleet/docs/' . $vehicleId . '/' . $filename;
            $origName = $file['name'];
        }

        $db->prepare("INSERT INTO fleet_documents (vehicle_id,doc_type,label,expiry_date,filename,file_path,original_name,notes,created_by) VALUES (?,?,?,?,?,?,?,?,?)")
           ->execute([$vehicleId, $docType, $label, $expiry, $filename, $filePath, $origName, $notes, $user['id']]);
        apiSuccess(['id' => (int)$db->lastInsertId()], 'Document saved.');
    }

    apiError('Unknown action.', 400);
} catch (Exception $e) {
    apiError('Error: ' . $e->getMessage(), 500);
}