<?php
require 'db.php';

$type = $_GET['type'] ?? '';

// Fetch customers
$customers = $conn->query("SELECT * FROM customers ORDER BY id DESC");

// Export PDF
if ($type == 'pdf') {
    require_once 'dompdf/autoload.inc.php';
    $html = "
        <h2 style='text-align:center;'>Customer List</h2>
        <table border='1' cellpadding='5' cellspacing='0' width='100%'>
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Phone</th>
                <th>Email</th>
                <th>Address</th>
            </tr>
    ";

    $i = 1;
    while ($c = $customers->fetch_assoc()) {
        $html .= "
            <tr>
                <td>{$i}</td>
                <td>{$c['name']}</td>
                <td>{$c['phone']}</td>
                <td>{$c['email']}</td>
                <td>{$c['address']}</td>
            </tr>";
        $i++;
    }

    $html .= "</table>";

    $dompdf = new Dompdf\Dompdf();
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    $dompdf->stream("customers.pdf", ["Attachment" => 1]);
    exit;
}

// Export Excel
if ($type == 'excel') {
    require 'vendor/autoload.php';
    $sp = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $sp->getActiveSheet();

    // Headers
    $sheet->setCellValue('A1', '#');
    $sheet->setCellValue('B1', 'Name');
    $sheet->setCellValue('C1', 'Phone');
    $sheet->setCellValue('D1', 'Email');
    $sheet->setCellValue('E1', 'Address');

    $i = 2;
    $n = 1;
    while ($c = $customers->fetch_assoc()) {
        $sheet->setCellValue("A$i", $n);
        $sheet->setCellValue("B$i", $c['name']);
        $sheet->setCellValue("C$i", $c['phone']);
        $sheet->setCellValue("D$i", $c['email']);
        $sheet->setCellValue("E$i", $c['address']);
        $i++;
        $n++;
    }

    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=customers.xlsx");

    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($sp);
    $writer->save("php://output");
    exit;
}

echo "Invalid export type.";
