<?php
require_once __DIR__ . '/../../core/config.php';
require_once __DIR__ . '/../../core/session.php';
require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/../../core/auth.php';
require_once __DIR__ . '/../../core/permissions.php';
require_once __DIR__ . '/../../services/billing/BillingDispatchGuideService.php';

require_login();
csrf_require_valid_request();
header('Content-Type: application/json; charset=utf-8');
if (!user_can('billing.issue.dispatch_guide') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success'=>false,'message'=>'No tienes permisos para preparar guías de despacho.'));
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('success'=>false,'message'=>'Método no permitido.'));
    exit;
}
try {
    $service = new BillingDispatchGuideService(db());
    $result = $service->previewGuide(array(
        'environment'=>$_POST['environment'] ?? 'sandbox',
        'source_type'=>$_POST['source_type'] ?? 'quote',
        'source_id'=>$_POST['source_id'] ?? 0,
        'issue_date'=>$_POST['issue_date'] ?? date('Y-m-d'),
        'guide_type'=>$_POST['guide_type'] ?? 1,
        'transfer_type'=>$_POST['transfer_type'] ?? 2,
        'dispatch_address'=>$_POST['dispatch_address'] ?? '',
        'dispatch_district'=>$_POST['dispatch_district'] ?? '',
        'dispatch_city'=>$_POST['dispatch_city'] ?? '',
        'observations'=>$_POST['observations'] ?? '',
        'lines_json'=>$_POST['lines_json'] ?? '[]'
    ), current_user_id());
    echo json_encode(array('success'=>true,'data'=>$result), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(array('success'=>false,'message'=>$e->getMessage()), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}
