<?php
require_once __DIR__ . '/../../../core/auth.php';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../../../libs/phpmailer/src/Exception.php';
require_once __DIR__ . '/../../../libs/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/../../../libs/phpmailer/src/SMTP.php';

use Dompdf\Dompdf;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;


$pdo = db();
$id = (int)($_GET['id'] ?? 0);

$head = $pdo->prepare("SELECT r.*, b.TaxRate, br.BranchName FROM SalesReceipt r
  JOIN BranchSettings b ON b.BranchID=r.BranchID
  JOIN Branches br ON br.BranchID=r.BranchID
  WHERE r.ReceiptID=?");
$head->execute([$id]);
$h = $head->fetch();
if(!$h || empty($h['CustomerEmail'])) exit;

$det = $pdo->prepare("SELECT * FROM SalesReceiptDetails WHERE ReceiptID=?");
$det->execute([$id]);
$rows = $det->fetchAll();

ob_start();
include __DIR__ . '/tpl_pdf.php';
$html = ob_get_clean();

$dompdf = new Dompdf();
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A5', 'portrait');
$dompdf->render();
$pdf = $dompdf->output();

$mail = new PHPMailer(true);
try{
  $mail->isSMTP();
  $mail->Host = 'smtp.example.com';
  $mail->SMTPAuth = true;
  $mail->Username = 'no-reply@example.com';
  $mail->Password = 'PASSWORD';
  $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
  $mail->Port = 587;

  $mail->setFrom('no-reply@example.com', 'POS');
  $mail->addAddress($h['CustomerEmail']);
  $mail->Subject = "فاتورتك #{$id}";
  $mail->Body    = "مرفق فاتورة الشراء. شكرًا لتعاملك معنا.";
  $mail->addStringAttachment($pdf, "receipt-{$id}.pdf", 'base64', 'application/pdf');

  $mail->send();
}catch(\Throwable $e){
  // سجل الخطأ لو حبيت
}
