<?php
require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../includes/admin-functions.php';

// Provera da li je korisnik prijavljen kao admin
if (!is_admin()) {
    header('Location: /admin/login.php');
    exit;
}

// Dobijanje formata za export
$format = isset($_GET['format']) ? strtolower($_GET['format']) : 'csv';

// Filteri
$status = isset($_GET['status']) ? $_GET['status'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Izgradnja upita
$conditions = [];
$params = [];

if (!empty($status) && in_array($status, ['pending', 'processing', 'shipped', 'delivered', 'canceled'])) {
    $conditions[] = "o.status = ?";
    $params[] = $status;
}

if (!empty($date_from)) {
    $conditions[] = "o.created_at >= ?";
    $params[] = $date_from . " 00:00:00";
}

if (!empty($date_to)) {
    $conditions[] = "o.created_at <= ?";
    $params[] = $date_to . " 23:59:59";
}

if (!empty($search)) {
    $conditions[] = "(o.order_number LIKE ? OR o.name LIKE ? OR o.email LIKE ? OR o.phone LIKE ?)";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
}

$where_clause = !empty($conditions) ? "WHERE " . implode(" AND ", $conditions) : "";

// Dohvatanje porudžbina za export
$sql = "
    SELECT 
        o.id,
        o.order_number,
        o.name,
        o.email,
        o.phone,
        o.address,
        o.city,
        o.zip,
        o.total,
        o.shipping_method,
        o.payment_method,
        o.notes,
        o.status,
        o.created_at,
        (SELECT COUNT(*) FROM order_items oi WHERE oi.order_id = o.id) as item_count
    FROM orders o
    {$where_clause}
    ORDER BY o.created_at DESC
";

$orders = get_rows($sql, $params);

// Definisanje naziva datoteke
$filename = 'hugong-porudzbine-' . date('Y-m-d');

// Definisanje zaglavlja kolona
$headers = [
    'ID', 
    'Broj porudžbine', 
    'Ime i prezime', 
    'Email', 
    'Telefon', 
    'Adresa', 
    'Grad', 
    'Poštanski broj',
    'Ukupno',
    'Način dostave',
    'Način plaćanja', 
    'Napomena',
    'Status',
    'Datum',
    'Broj stavki'
];

// Priprema podataka za export
$data = [];
foreach ($orders as $order) {
    $data[] = [
        $order['id'],
        $order['order_number'],
        $order['name'],
        $order['email'],
        $order['phone'],
        $order['address'],
        $order['city'],
        $order['zip'],
        $order['total'],
        $order['shipping_method'],
        $order['payment_method'],
        $order['notes'],
        get_order_status_name($order['status']),
        date('d.m.Y. H:i', strtotime($order['created_at'])),
        $order['item_count']
    ];
}

// Export prema odabranom formatu
switch ($format) {
    case 'csv':
        export_csv($filename, $headers, $data);
        break;
        
    case 'excel':
        export_excel($filename, $headers, $data);
        break;
        
    case 'pdf':
        export_pdf($filename, $headers, $data);
        break;
        
    default:
        export_csv($filename, $headers, $data);
        break;
}

/**
 * Export u CSV formatu
 */
function export_csv($filename, $headers, $data) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Dodavanje BOM za UTF-8
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    
    // Dodavanje zaglavlja
    fputcsv($output, $headers, ';');
    
    // Dodavanje podataka
    foreach ($data as $row) {
        fputcsv($output, $row, ';');
    }
    
    fclose($output);
    exit;
}

/**
 * Export u Excel formatu
 */
function export_excel($filename, $headers, $data) {
    if (!class_exists('PhpOffice\PhpSpreadsheet\Spreadsheet')) {
        // Ako PhpSpreadsheet nije instaliran, izvezi kao CSV
        export_csv($filename, $headers, $data);
        return;
    }
    
    require_once '../../vendor/autoload.php';
    
    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    
    // Dodavanje zaglavlja
    $col = 1;
    foreach ($headers as $header) {
        $sheet->setCellValueByColumnAndRow($col++, 1, $header);
    }
    
    // Dodavanje podataka
    $row = 2;
    foreach ($data as $rowData) {
        $col = 1;
        foreach ($rowData as $value) {
            $sheet->setCellValueByColumnAndRow($col++, $row, $value);
        }
        $row++;
    }
    
    // Stilizovanje tabele
    $lastColumn = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex(count($headers));
    $headerRange = 'A1:' . $lastColumn . '1';
    
    $sheet->getStyle($headerRange)->getFont()->setBold(true);
    $sheet->getStyle($headerRange)->getFill()
        ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
        ->getStartColor()->setRGB('DDDDDD');
    
    // Auto-veličina kolona
    foreach (range('A', $lastColumn) as $columnID) {
        $sheet->getColumnDimension($columnID)->setAutoSize(true);
    }
    
    // Kreiranje writer-a i slanje fajla
    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="' . $filename . '.xlsx"');
    header('Cache-Control: max-age=0');
    
    $writer->save('php://output');
    exit;
}

/**
 * Export u PDF formatu
 */
function export_pdf($filename, $headers, $data) {
    // Provera da li je instaliran TCPDF ili neki drugi PDF library
    if (!class_exists('TCPDF') && !class_exists('FPDF') && !class_exists('Dompdf\Dompdf')) {
        // Ako PDF library nije instaliran, izvezi kao CSV
        export_csv($filename, $headers, $data);
        return;
    }
    
    // Ako je instaliran TCPDF
    if (class_exists('TCPDF')) {
        require_once '../../vendor/autoload.php';
        
        $pdf = new TCPDF('L', 'mm', 'A4', true, 'UTF-8');
        
        // Podešavanje dokumenta
        $pdf->SetCreator('Hugong Aparati');
        $pdf->SetAuthor('Hugong Admin');
        $pdf->SetTitle('Porudžbine');
        $pdf->SetSubject('Izvoz porudžbina');
        
        // Uklanjanje headera i footera
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        
        // Dodavanje stranice
        $pdf->AddPage();
        
        // Postavljanje fonta
        $pdf->SetFont('dejavusans', '', 10);
        
        // Kreiranje tabele
        $html = '<table border="1" cellpadding="5">';
        
        // Zaglavlje tabele
        $html .= '<tr style="background-color: #EEEEEE; font-weight: bold;">';
        foreach ($headers as $header) {
            $html .= '<th>' . $header . '</th>';
        }
        $html .= '</tr>';
        
        // Podaci tabele
        foreach ($data as $row) {
            $html .= '<tr>';
            foreach ($row as $cell) {
                $html .= '<td>' . $cell . '</td>';
            }
            $html .= '</tr>';
        }
        
        $html .= '</table>';
        
        // Ispis HTML-a
        $pdf->writeHTML($html, true, false, true, false, '');
        
        // Zatvaranje i slanje PDF dokumenta
        $pdf->Output($filename . '.pdf', 'D');
        exit;
    }
    
    // Ako je instaliran FPDF
    if (class_exists('FPDF')) {
        require_once '../../vendor/tcpdf.php';
        
        $pdf = new FPDF('L', 'mm', 'A4');
        $pdf->AddPage();
        $pdf->SetFont('Arial', 'B', 10);
        
        // Širina kolona (prilagodite po potrebi)
        $column_widths = [10, 30, 40, 40, 30, 40, 20, 20, 20, 25, 25, 40, 25, 30, 15];
        
        // Zaglavlje
        for ($i = 0; $i < count($headers); $i++) {
            $pdf->Cell($column_widths[$i], 10, iconv('UTF-8', 'windows-1252', $headers[$i]), 1);
        }
        $pdf->Ln();
        
        // Podaci
        $pdf->SetFont('Arial', '', 10);
        foreach ($data as $row) {
            for ($i = 0; $i < count($row); $i++) {
                $pdf->Cell($column_widths[$i], 10, iconv('UTF-8', 'windows-1252', $row[$i]), 1);
            }
            $pdf->Ln();
        }
        
        $pdf->Output($filename . '.pdf', 'D');
        exit;
    }
    
    // Ako je instaliran Dompdf
    if (class_exists('Dompdf\Dompdf')) {
        require_once '../../vendor/autoload.php';
        
        $dompdf = new \Dompdf\Dompdf();
        
        // HTML sadržaj
        $html = '
        <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
            <style>
                body { font-family: DejaVu Sans, sans-serif; }
                table { border-collapse: collapse; width: 100%; }
                th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                th { background-color: #f2f2f2; }
            </style>
        </head>
        <body>
            <h2>Porudžbine - Izvoz</h2>
            <table>
                <thead>
                    <tr>';
        
        foreach ($headers as $header) {
            $html .= '<th>' . $header . '</th>';
        }
        
        $html .= '</tr>
                </thead>
                <tbody>';
        
        foreach ($data as $row) {
            $html .= '<tr>';
            foreach ($row as $cell) {
                $html .= '<td>' . $cell . '</td>';
            }
            $html .= '</tr>';
        }
        
        $html .= '</tbody>
            </table>
        </body>
        </html>';
        
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'landscape');
        $dompdf->render();
        $dompdf->stream($filename . '.pdf', ['Attachment' => true]);
        exit;
    }
}