<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

echo "<pre>🚨 Debug Mode On</pre>";
require __DIR__ . '/../includes/db.php';
require __DIR__ . '/../vendor/autoload.php'; // ✅ المسار الصحيح (صعود مجلد واحد فقط)

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;

$cust_id = (int)($_POST['customer_id'] ?? 0);
if (!$cust_id) exit('❌ لا يوجد عميل محدد.');

$movements = [];

// 🔹 فواتير المبيعات
$q1 = $pdo->prepare("
  SELECT si.date, CONCAT('فاتورة مبيعات رقم ', si.id) AS descp,
         si.total AS debit, 0 AS credit
  FROM sales_invoices si
  WHERE si.customer_id = ?
");
$q1->execute([$cust_id]);
foreach($q1 as $r){ $movements[] = $r; }

// 🔹 قبض من العميل
$q2 = $pdo->prepare("
  SELECT date, CONCAT('قبض من العميل: ', COALESCE(note,'')) AS descp,
         0 AS debit, amount AS credit
  FROM customer_money 
  WHERE customer_id=? AND type='in'
");
$q2->execute([$cust_id]);
foreach($q2 as $r){ $movements[] = $r; }

// 🔹 دفع للعميل (مرتجع)
$q3 = $pdo->prepare("
  SELECT date, CONCAT('دفع للعميل: ', COALESCE(note,'')) AS descp,
         amount AS debit, 0 AS credit
  FROM customer_money 
  WHERE customer_id=? AND type='out'
");
$q3->execute([$cust_id]);
foreach($q3 as $r){ $movements[] = $r; }

usort($movements, fn($a,$b)=>strcmp($a['date'],$b['date']));

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('كشف حساب عميل');

// رؤوس الأعمدة
$headers = ['التاريخ', 'البيان', 'مدين', 'دائن', 'الرصيد'];
$col = 'A';
foreach ($headers as $header) {
  $sheet->setCellValue($col.'1', $header);
  $sheet->getStyle($col.'1')->applyFromArray([
    'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
    'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '0B5394']],
    'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER]
  ]);
  $col++;
}

// تعبئة البيانات
$row = 2; $run = 0; $d = 0; $c = 0;
foreach ($movements as $m) {
  $run += ($m['debit'] - $m['credit']);
  $d += $m['debit']; $c += $m['credit'];
  $sheet->setCellValue("A$row", $m['date']);
  $sheet->setCellValue("B$row", $m['descp']);
  $sheet->setCellValue("C$row", $m['debit']);
  $sheet->setCellValue("D$row", $m['credit']);
  $sheet->setCellValue("E$row", $run);
  $row++;
}

// صف الإجمالي
$sheet->setCellValue("A$row", 'الإجمالي');
$sheet->mergeCells("A$row:B$row");
$sheet->setCellValue("C$row", $d);
$sheet->setCellValue("D$row", $c);
$sheet->setCellValue("E$row", $d - $c);

$sheet->getStyle("A$row:E$row")->applyFromArray([
  'font' => ['bold' => true],
  'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'D9EAD3']],
]);

foreach (range('A', 'E') as $col)
  $sheet->getColumnDimension($col)->setAutoSize(true);

$writer = new Xlsx($spreadsheet);
$filename = "customer_statement_{$cust_id}.xlsx";

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment; filename=\"$filename\"");
$writer->save('php://output');
exit;
