<?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);
}

$search = $_GET['search'] ?? '';
$sql = "
SELECT invoices.id, customers.name, customers.phone, invoices.invoice_date, invoices.total
FROM invoices
JOIN customers ON invoices.customer_id = customers.id
WHERE customers.name LIKE ? OR customers.phone LIKE ?
ORDER BY invoices.id DESC
";

$stmt = $conn->prepare($sql);
$param = "%$search%";
$stmt->bind_param("ss", $param, $param);
$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <title>سجل الفواتير</title>
</head>
<body>
  <h2>سجل الفواتير</h2>

  <form method="GET">
    <input type="text" name="search" placeholder="ابحث باسم العميل أو الهاتف" value="<?= htmlspecialchars($search) ?>">
    <button type="submit">بحث</button>
  </form>

  <table border="1" cellpadding="6" style="width:100%; margin-top:20px;">
    <tr>
      <th>رقم الفاتورة</th>
      <th>العميل</th>
      <th>الهاتف</th>
      <th>التاريخ</th>
      <th>الإجمالي</th>
      <th>عرض</th>
    </tr>
    <?php while ($row = $result->fetch_assoc()): ?>
      <tr>
        <td><?= $row['id'] ?></td>
        <td><?= htmlspecialchars($row['name']) ?></td>
        <td><?= htmlspecialchars($row['phone']) ?></td>
        <td><?= $row['invoice_date'] ?></td>
        <td><?= $row['total'] ?> ريال</td>
        <td><a href="view_invoice.php?id=<?= $row['id'] ?>" target="_blank">عرض PDF</a></td>
      </tr>
    <?php endwhile; ?>
  </table>
</body>
</html>