<?php
session_start();
if (!isset($_SESSION['admin'])) {
  header("Location: login_admin.php");
  exit;
}

require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

if (!isset($_POST['order_ids']) || !is_array($_POST['order_ids'])) {
  die("Tidak ada data yang dipilih.");
}

<?php
$host = "localhost";
$user = "odmr9632_userdb";
$pass = "@Sukabumi2018";
$db   = "odmr9632_order_db";

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
  die("Koneksi gagal: " . $conn->connect_error);
}
?>
if ($conn->connect_error) {
  die("Koneksi gagal: " . $conn->connect_error);
}

$ids = array_map('intval', $_POST['order_ids']);
$idList = implode(',', $ids);
$sql = "SELECT * FROM orders WHERE id IN ($idList)";
$result = $conn->query($sql);

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

$headers = [
  'No', 'Tanggal', 'Produk', 'CS', 'Customer', 'Qty', 'Harga', 'Fee COD', 'Ongkir',
  'Provinsi', 'Kota', 'Kecamatan', 'Alamat', 'Status Pengiriman', 'No Resi', 'Status Paket'
];
$sheet->fromArray($headers, NULL, 'A1');

$rowNum = 2;
$no = 1;
while ($r = $result->fetch_assoc()) {
  $sheet->fromArray([
    $no++,
    $r['tanggal'], $r['nama_produk'], $r['nama_cs'], $r['nama_customer'], $r['qty'],
    $r['harga_jual'], $r['fee_cod'], $r['ongkir'],
    $r['provinsi'], $r['kota'], $r['kecamatan'], $r['alamat'],
    $r['status_pengiriman'], $r['no_resi'], $r['status_paket']
  ], NULL, 'A' . $rowNum++);
}

$filename = "data_order_" . date('Ymd_His') . ".xlsx";
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment; filename=\"$filename\"");
header('Cache-Control: max-age=0');

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