<?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();
header('Content-Type: application/json; charset=utf-8');
if (!user_can('billing.dispatch_guides') && !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 ver el origen de la guía.'));
    exit;
}
try {
    $service = new BillingDispatchGuideService(db());
    $source = $service->getSource($_GET['source_type'] ?? 'quote', $_GET['source_id'] ?? 0, $_GET['environment'] ?? 'sandbox');
    echo json_encode(array('success'=>true,'source'=>$source), 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);
}
