<?php
require 'vendor/autoload.php'; // Ensure this path matches your Composer autoload location
require_once('includes/load.php'); // Load database connection
global $db;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// Fetch data from the database
$sql = "SELECT id, nama_toko, pic, alamat, nomor_telp FROM pelanggan;"; // Replace 'your_table_name' with the actual table name
$result = $db->query($sql);

// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();

// Header columns
$sheet->setCellValue('A1', 'No');
$sheet->setCellValue('B1', 'Nama Toko');
$sheet->setCellValue('C1', 'PIC');
$sheet->setCellValue('D1', 'Alamat');
$sheet->setCellValue('E1', 'Telp');

// Add data from query to sheet
$rowNumber = 2; // Start from the second row (header is in the first row)
while ($row = $result->fetch_assoc()) {
  $sheet->setCellValue('A' . $rowNumber, $row['id']);
  $sheet->setCellValue('B' . $rowNumber, $row['nama_toko']);
  $sheet->setCellValue('C' . $rowNumber, $row['pic']);
  $sheet->setCellValue('D' . $rowNumber, $row['alamat']);
  $sheet->setCellValue('E' . $rowNumber, $row['nomor_telp']);
  $rowNumber++;
}

// Set filename for the Excel file
$filename = 'master_pelanggan.xlsx';

// Set headers for Excel file download
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');

// Write Excel file to output
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;