<?php
require('../../vendor/autoload.php');
include_once('../../includes/db.php');
use Dompdf\Dompdf;

ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

// Get Order
$order_id = $_GET['order_id'] ?? null;
if (!$order_id) {
    echo json_encode(["status" => false, "message" => "Order ID is required"]);
    exit;
}

$order = fetchOne("SELECT * FROM orders WHERE id = ?", [$order_id]);
if (!$order) {
    echo json_encode(["status" => false, "message" => "Order not found"]);
    exit;
}

$user = fetchOne("SELECT * FROM users WHERE id = ?", [$order['user_id']]);
if (!$user) {
    echo json_encode(["status" => false, "message" => "User not found"]);
    exit;
}

$order_items = fetchAll("SELECT * FROM order_items WHERE order_id = ?", [$order_id]);

$total = 0;
$items_html = "";

foreach ($order_items as $item) {
    $qty = (int)$item['quantity'];
    $price = (float)$item['price'];
    $subtotal = $qty * $price;
    $total += $subtotal;

    $product = fetchOne("SELECT name FROM products WHERE id = ?", [$item['product_id']]);
    $productName = $product ? $product['name'] : "Unknown Product";

    $items_html .= "
        <tr>
          <td>{$productName}</td>
          <td>{$qty}</td>
          <td>" . number_format($price, 2) . " BHD</td>
          <td>" . number_format($subtotal, 2) . " BHD</td>
        </tr>";
}

$createdAt = $order['created_at'];
$paymentType = $order['payment_type'] ?? 'COD';
$status = ucfirst($order['status'] ?? 'Pending');

$address = $order['address'] ?? 'Not provided';
$location = $order['location'] ?? '';
$shipping_address = $address;
if (!empty($location)) {
    $shipping_address .= "<br><small>📍 {$location}</small>";
}

$delivery_fee = floatval($order['delivery_fee'] ?? 0);
$final_total = $total + $delivery_fee;

$formatted_total = number_format($total, 2);
$formatted_delivery = number_format($delivery_fee, 2);
$formatted_final = number_format($final_total, 2);

$html = <<<HTML
<html>
<head>
  <meta charset="UTF-8">
  <style>
    * { box-sizing: border-box; }
    body {
      font-family: 'Segoe UI', 'Helvetica Neue', sans-serif;
      font-size: 12px;
      margin: 0;
      padding: 30px;
      background: #f9f9f9;
      color: #333;
    }
    .invoice {
      background: #fff;
      padding: 30px;
      border-radius: 10px;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 2px solid #0C3D3E;
      padding-bottom: 10px;
      margin-bottom: 25px;
    }
    .header h1 {
      margin: 0;
      font-size: 28px;
      color: #0C3D3E;
    }
    .header-details {
      text-align: right;
      font-size: 11px;
    }
    .section {
      margin-bottom: 25px;
    }
    .section-title {
      font-size: 14px;
      font-weight: bold;
      color: #0C3D3E;
      margin-bottom: 8px;
      border-left: 4px solid #0C3D3E;
      padding-left: 10px;
    }
    .info-box {
      background: #f1f1f1;
      padding: 10px 15px;
      border-radius: 6px;
      font-size: 12px;
    }
    .info-table {
      width: 100%;
      margin-top: 10px;
    }
    .info-table td {
      padding: 5px;
      vertical-align: top;
    }
    .items-table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 10px;
      font-size: 11px;
    }
    .items-table th, .items-table td {
      border: 1px solid #ccc;
      padding: 8px;
      text-align: left;
    }
    .items-table th {
      background: #0C3D3E;
      color: white;
    }
    .totals {
      width: 250px;
      float: right;
      margin-top: 20px;
      font-size: 12px;
    }
    .totals td {
      padding: 6px;
    }
    .totals .label {
      font-weight: bold;
    }
    .stamp {
  position: absolute;
  bottom: 150px; /* or top: Xpx depending on where you want it */
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  z-index: 0;
}

    .stamp img {
      height: 400px;
    }
    .footer {
      clear: both;
      text-align: center;
      font-size: 10px;
      color: #777;
      border-top: 1px dashed #ccc;
      margin-top: 50px;
      padding-top: 10px;
    }
  </style>
</head>
<body>
  <div class="invoice">
    <div class="header">
      <h1>INVOICE</h1>
      <div class="header-details">
        <strong>Al Rayah Shopp</strong><br>
        Road 0000, Manama, Capital Governorate, Bahrain<br>
        support@developer-bh.live.com
      </div>
    </div>

    <div class="section">
      <div class="section-title">Customer Information</div>
      <div class="info-box">
        <table class="info-table">
          <tr>
            <td><strong>Name:</strong> {$user['name']}</td>
            <td><strong>Phone:</strong> {$user['phone']}</td>
          </tr>
          <tr>
            <td colspan="2"><strong>Shipping Address:</strong><br>{$shipping_address}</td>
          </tr>
        </table>
      </div>
    </div>

    <div class="section">
      <div class="section-title">Order Details</div>
      <div class="info-box">
        <table class="info-table">
          <tr>
            <td><strong>Invoice #:</strong> {$order_id}</td>
            <td><strong>Date:</strong> {$createdAt}</td>
          </tr>
          <tr>
            <td><strong>Payment:</strong> {$paymentType}</td>
            <td><strong>Status:</strong> {$status}</td>
          </tr>
        </table>
      </div>
    </div>

    <div class="section">
      <div class="section-title">Items</div>
      <table class="items-table">
        <thead>
          <tr>
            <th>Product</th>
            <th>Qty</th>
            <th>Unit Price</th>
            <th>Subtotal</th>
          </tr>
        </thead>
        <tbody>
          {$items_html}
        </tbody>
      </table>
    </div>

    <table class="totals">
      <tr>
        <td class="label">Subtotal:</td>
        <td>{$formatted_total} BHD</td>
      </tr>
      <tr>
        <td class="label">Delivery Fee:</td>
        <td>{$formatted_delivery} BHD</td>
      </tr>
      <tr>
        <td class="label">Total:</td>
        <td><strong>{$formatted_final} BHD</strong></td>
      </tr>
    </table>

    <div class="stamp">
      <img src="https://alhussain-voice.com/printshop/assets/stamp.png" alt="Stamp">
    </div>

    <div class="footer">
      Thank you for your business!<br>
      This is a system-generated invoice and does not require a signature.
    </div>
  </div>
</body>
</html>
HTML;


$dompdf = new Dompdf();
$dompdf->set_option('isRemoteEnabled', true); // Important to allow external images
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

$pdfOutput = $dompdf->output();
$save_path = $_SERVER['DOCUMENT_ROOT'] . "/printshop/invoices/invoice_{$order_id}.pdf";
file_put_contents($save_path, $pdfOutput);

// Debug display version (optional for testing in browser)
// $dompdf->stream("invoice_{$order_id}.pdf", array("Attachment" => false)); exit;

if (file_exists($save_path)) {
    echo json_encode([
        "status" => true,
        "message" => "Invoice generated successfully.",
        "url" => "https://alhussain-voice.com/printshop/invoices/invoice_{$order_id}.pdf"
    ]);
} else {
    echo json_encode([
        "status" => false,
        "message" => "Failed to generate invoice. Tried saving to: $save_path"
    ]);
}
?>
