<?php
require_once('tcpdf/tcpdf.php');

$host = "localhost";
$user = "blenco1_billing_system";
$password = "Hafshan@2552";
$dbname = "blenco1_billing_system";

$conn = new mysqli($host, $user, $password, $dbname);
if ($conn->connect_error) {
    die("فشل الاتصال: " . $conn->connect_error);
}

$invoice_id = $_GET['id'] ?? 0;

$sql = "
SELECT c.name, c.phone, i.description, i.quantity, i.unit_price, i.total, i.invoice_date
FROM invoices i
JOIN customers c ON i.customer_id = c.id
WHERE i.id = ?
LIMIT 1
";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("لم يتم العثور على الفاتورة.");
}

$row = $result->fetch_assoc();

$pdf = new TCPDF();
$pdf->setRTL(true);
$pdf->SetFont('dejavusans', '', 12);
$pdf->AddPage();

$html = <<<EOD
<h2 style="text-align: center;">فاتورة رقم {$invoice_id}</h2>
<p><strong>العميل:</strong> {$row['name']}</p>
<p><strong>الهاتف:</strong> {$row['phone']}</p>
<p><strong>التاريخ:</strong> {$row['invoice_date']}</p>
<table border="1" cellpadding="6" style="text-align: right;" dir="rtl">
  <tr>
    <th>الوصف</th>
    <th>الكمية</th>
    <th>سعر الوحدة</th>
    <th>الإجمالي</th>
  </tr>
  <tr>
    <td>{$row['description']}</td>
    <td>{$row['quantity']}</td>
    <td>{$row['unit_price']}</td>
    <td>{$row['total']}</td>
  </tr>
</table>
<h3 style="text-align:right;">الإجمالي الكلي: {$row['total']} ريال</h3>
EOD;

$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output("فاتورة_{$row['name']}_{$invoice_id}.pdf", 'I');
?>