<?php
// cotizacion-billing-export.php - Exportar a CSV (abrible con Excel)
include __DIR__ . '/core/autoload.php';

$con = Database::getCon();

$doctorId = isset($_GET['doctor_id']) ? intval($_GET['doctor_id']) : 0;
$status = $_GET['status'] ?? '';
$dateFrom = $_GET['cotiz_date_from'] ?? ($_GET['date_from'] ?? '');
$dateTo = $_GET['cotiz_date_to'] ?? ($_GET['date_to'] ?? '');

$where = ['c.is_active = 1'];
$params = [];
$types = '';

if ($doctorId > 0) {
    $where[] = 'c.professional_id = ?';
    $params[] = $doctorId;
    $types .= 'i';
}
if ($status === 'particular' || $status === 'facturado') {
    $where[] = 'cd.billing_type = ?';
    $params[] = $status;
    $types .= 's';
}
if ($dateFrom) {
    $where[] = 'DATE(c.date) >= ?';
    $params[] = $dateFrom;
    $types .= 's';
}
if ($dateTo) {
    $where[] = 'DATE(c.date) <= ?';
    $params[] = $dateTo;
    $types .= 's';
}

$whereSql = 'WHERE ' . implode(' AND ', $where);

$sql = "
    SELECT
        c.id AS cotizacion_id,
        c.date,
        c.status AS cotiz_status,
        CONCAT(u.name, ' ', u.lastname) AS doctor_name,
        p.name AS patient_name,
        cd.description,
        cd.quantity,
        cd.subtotal,
        cd.billing_type,
        c.notes
    FROM cotizacion c
    INNER JOIN cotizacion_detalle cd ON cd.cotizacion_id = c.id
    LEFT JOIN user u ON c.professional_id = u.id
    LEFT JOIN pacient p ON c.patient_id = p.id
    $whereSql
    ORDER BY c.date DESC, doctor_name
";

$stmt = $con->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$filename = 'pagos_cotizaciones_' . date('Y-m-d_His') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');

$out = fopen('php://output', 'w');
// BOM for Excel UTF-8
fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
fputcsv($out, ['Fecha', 'Orden #', 'Doctor', 'Paciente', 'Descripcion', 'Cantidad', 'Subtotal (Bs)', 'Tipo Facturacion', 'Estado Cotizacion', 'Notas']);

$cotizStatusLabels = [
    'draft' => 'Borrador',
    'sent' => 'Enviada',
    'accepted' => 'Aceptada',
    'rejected' => 'Rechazada',
    'expired' => 'Expirada',
];

foreach ($rows as $r) {
    fputcsv($out, [
        date('d/m/Y', strtotime($r['date'])),
        $r['cotizacion_id'],
        $r['doctor_name'],
        $r['patient_name'],
        $r['description'],
        $r['quantity'],
        number_format((float)$r['subtotal'], 2, '.', ''),
        $r['billing_type'],
        $cotizStatusLabels[$r['cotiz_status']] ?? $r['cotiz_status'],
        $r['notes'],
    ]);
}
fclose($out);