<?php

declare(strict_types=1);
namespace Controllers;

use Config\Database;
use Helpers\Auth;
use Helpers\Response;
use Repositories\OrderRepository;

final class UserOrderController
{
    public function index(): never
    {
        try {
            $u = Auth::requireUser();
            Response::success((new OrderRepository())->listForUser((int) $u['id']));
        } catch (\Throwable $e) {
            Response::error($e->getMessage(), 401);
        }
    }

    public function show(string $orderNumber): never
    {
        try {
            $u = Auth::requireUser();
            $o = (new OrderRepository())->detailForUser((int) $u['id'], $orderNumber);
            if (!$o) Response::error('Order not found', 404);
            Response::success($o);
        } catch (\Throwable $e) {
            Response::error($e->getMessage(), 401);
        }
    }

    /**
     * GET /api/orders/{orderNumber}/invoice
     *
     * Returns a rendered HTML invoice page (not JSON).
     * Opens in a new browser tab — fetched via JS with Bearer token,
     * then displayed as a Blob URL.
     */
    public function invoice(string $orderNumber): never
    {
        /* ── Auth ──────────────────────────────────────────────────────── */
        $user = Auth::user();
        if (!$user) {
            header('Content-Type: application/json');
            http_response_code(401);
            echo json_encode(['success' => false, 'message' => 'Authentication required']);
            exit();
        }

        $userId = (int) $user['id'];
        $db     = Database::connection();

        /* ── Fetch order ───────────────────────────────────────────────── */
        $stmt = $db->prepare('
            SELECT * FROM orders
            WHERE  order_number = :order_number
            AND    user_id      = :user_id
            LIMIT  1
        ');
        $stmt->execute(['order_number' => $orderNumber, 'user_id' => $userId]);
        $order = $stmt->fetch();

        if (!$order) {
            header('Content-Type: application/json');
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Order not found']);
            exit();
        }

        /* ── Fetch items with product image ────────────────────────────── */
       $stmt = $db->prepare('
    SELECT oi.product_name,
           oi.product_slug,
           oi.quantity,
           oi.unit_price,
           oi.total_price,
           NULL AS image_url
    FROM   order_items oi
    WHERE  oi.order_id = :order_id
');
$stmt->execute(['order_id' => (int) $order['id']]);
$items = $stmt->fetchAll();
        /* ── Totals ────────────────────────────────────────────────────── */
        $subtotal       = (float) ($order['subtotal']        ?? 0);
        $shippingAmount = (float) ($order['shipping_amount'] ?? 0);
        $discountAmount = (float) ($order['discount_amount'] ?? 0);
        $taxAmount      = (float) ($order['tax_amount']      ?? 0);
        $totalAmount    = (float) ($order['total_amount']    ?? 0);

        /* ── Invoice meta ──────────────────────────────────────────────── */
        $orderId       = (int) $order['id'];
        $invoiceNumber = 'INV-' . date('Y') . '-' . str_pad((string) $orderId, 5, '0', STR_PAD_LEFT);
        $invoiceDate   = date('d M Y', strtotime((string) $order['created_at']));
        $orderDate     = date('d M Y, h:i A', strtotime((string) $order['created_at']));

        /* ── Status pill class ─────────────────────────────────────────── */
        $oStatus = strtolower((string) ($order['order_status']  ?? ''));
        $pStatus = strtolower((string) ($order['payment_status'] ?? ''));

        $oPillClass = match (true) {
            in_array($oStatus, ['confirmed', 'delivered', 'completed'], true) => 'pill-green',
            in_array($oStatus, ['processing', 'shipped'],               true) => 'pill-blue',
            in_array($oStatus, ['cancelled', 'failed'],                 true) => 'pill-grey',
            default                                                            => 'pill-amber',
        };
        $pPillClass = match (true) {
            in_array($pStatus, ['paid', 'captured'],   true) => 'pill-green',
            in_array($pStatus, ['pending', 'created'],  true) => 'pill-amber',
            default                                           => 'pill-grey',
        };

        /* ── Helpers ───────────────────────────────────────────────────── */
        $inr = static fn (float $v): string => '₹' . number_format($v, 2);
        $esc = static fn (mixed $v): string =>
            htmlspecialchars((string) ($v ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

        /* ── Render HTML ───────────────────────────────────────────────── */
        header('Content-Type: text/html; charset=UTF-8');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        ob_start();
        // phpcs:disable
        ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Invoice <?= $esc($invoiceNumber) ?> — Anshul Food Products</title>
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: 'Segoe UI', Arial, sans-serif; background: #f4f0e8; color: #1a0d06; min-height: 100vh; padding: 40px 20px 60px; }
    @media print { body { background: #fff; padding: 0; } .no-print { display: none !important; } .invoice-card { box-shadow: none !important; } }
    .invoice-card { max-width: 860px; margin: 0 auto; background: #fff; border-radius: 4px; box-shadow: 0 4px 40px rgba(0,0,0,.10); overflow: hidden; }
    .inv-header { background: #1a0d06; padding: 36px 48px 32px; display: flex; align-items: flex-start; justify-content: space-between; gap: 24px; flex-wrap: wrap; }
    .brand-name { font-family: Georgia, serif; font-size: 28px; font-weight: 700; color: #fff; letter-spacing: .01em; line-height: 1.1; }
    .brand-sub { font-size: 9px; font-weight: 700; letter-spacing: .32em; text-transform: uppercase; color: rgba(216,168,79,.75); margin-top: 5px; }
    .brand-address { margin-top: 10px; font-size: 11px; color: rgba(255,253,248,.45); line-height: 1.7; }
    .inv-badge { text-align: right; }
    .inv-badge .label { font-size: 9px; font-weight: 800; letter-spacing: .3em; text-transform: uppercase; color: rgba(216,168,79,.70); }
    .inv-badge .number { font-family: Georgia, serif; font-size: 22px; font-weight: 700; color: #d8a84f; margin-top: 4px; white-space: nowrap; }
    .inv-badge .date { font-size: 11px; color: rgba(255,253,248,.40); margin-top: 5px; }
    .gold-line { height: 3px; background: linear-gradient(90deg,#d8a84f 0%,#e7c068 50%,#d8a84f 100%); }
    .inv-body { padding: 40px 48px; }
    .info-row { display: grid; grid-template-columns: 1fr 1fr; gap: 32px; margin-bottom: 36px; }
    .info-block h3 { font-size: 9px; font-weight: 800; letter-spacing: .28em; text-transform: uppercase; color: #d8a84f; border-bottom: 1px solid #e8e0d0; padding-bottom: 6px; margin-bottom: 12px; }
    .info-block p { font-size: 13px; line-height: 1.75; color: #3a2010; }
    .info-block p strong { color: #1a0d06; font-weight: 700; }
    .status-row { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 36px; }
    .pill { display: inline-flex; align-items: center; gap: 6px; padding: 5px 14px; border-radius: 100px; font-size: 11px; font-weight: 700; letter-spacing: .06em; text-transform: capitalize; }
    .pill-green { background: #e6f9ef; color: #15803d; }
    .pill-amber { background: #fff8e6; color: #b45309; }
    .pill-blue  { background: #e8f0fe; color: #1d4ed8; }
    .pill-grey  { background: #f3f4f6; color: #6b7280; }
    .pill-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; flex-shrink: 0; }
    .items-label { font-size: 9px; font-weight: 800; letter-spacing: .28em; text-transform: uppercase; color: #d8a84f; margin-bottom: 12px; }
    table { width: 100%; border-collapse: collapse; font-size: 13px; }
    thead th { background: #1a0d06; color: rgba(255,253,248,.65); font-size: 9px; font-weight: 800; letter-spacing: .18em; text-transform: uppercase; padding: 10px 14px; text-align: left; }
    thead th:last-child { text-align: right; }
    thead th:nth-child(2), thead th:nth-child(3) { text-align: center; }
    tbody tr { border-bottom: 1px solid #f0ece4; }
    tbody tr:last-child { border-bottom: none; }
    tbody td { padding: 13px 14px; vertical-align: middle; color: #2a1508; }
    tbody td:last-child { text-align: right; font-weight: 600; }
    tbody td:nth-child(2), tbody td:nth-child(3) { text-align: center; color: #5a3a1a; }
    .product-thumb { display: inline-flex; align-items: center; gap: 12px; }
    .product-thumb img { width: 40px; height: 40px; object-fit: cover; border-radius: 3px; border: 1px solid #e8e0d0; flex-shrink: 0; }
    .product-thumb-placeholder { width: 40px; height: 40px; border-radius: 3px; background: #f0ece4; border: 1px solid #e8e0d0; display: flex; align-items: center; justify-content: center; flex-shrink: 0; font-size: 16px; }
    .product-name { font-weight: 600; color: #1a0d06; }
    .product-slug { font-size: 10px; color: #a07040; margin-top: 2px; }
    .totals-wrap { display: flex; justify-content: flex-end; margin-top: 24px; }
    .totals-table { width: 280px; }
    .totals-table td { padding: 6px 0; font-size: 13px; color: #3a2010; }
    .totals-table td:last-child { text-align: right; font-weight: 600; color: #1a0d06; }
    .totals-table .grand td { padding-top: 12px; border-top: 2px solid #1a0d06; font-size: 15px; font-weight: 800; color: #1a0d06; }
    .totals-table .discount td, .totals-table .discount td:last-child { color: #15803d; }
    .inv-footer { background: #1a0d06; padding: 24px 48px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
    .inv-footer p { font-size: 11px; color: rgba(255,253,248,.38); }
    .inv-footer a { color: #d8a84f; text-decoration: none; }
    .print-bar { max-width: 860px; margin: 0 auto 20px; display: flex; justify-content: flex-end; }
    .btn-print { background: #1a0d06; color: #d8a84f; border: 1.5px solid #d8a84f; padding: 9px 22px; border-radius: 100px; font-size: 12px; font-weight: 700; letter-spacing: .08em; cursor: pointer; }
    .btn-print:hover { background: #2e1810; }
    @media (max-width:560px) { .info-row { grid-template-columns: 1fr; } .inv-header,.inv-body { padding: 28px 20px; } .inv-footer { padding: 20px; flex-direction: column; } }
  </style>
</head>
<body>

  <div class="print-bar no-print">
    <button class="btn-print" onclick="window.print()">🖨 Print / Save as PDF</button>
  </div>

  <div class="invoice-card">

    <div class="inv-header">
      <div>
        <div class="brand-name">Anshul Food Products</div>
        <div class="brand-sub">Premium Confectionery · Nashik</div>
        <div class="brand-address">
          Nashik, Maharashtra, India<br>
          +91 94227 58989 &nbsp;·&nbsp; info@anshulfoodproduct.com
        </div>
      </div>
      <div class="inv-badge">
        <div class="label">Tax Invoice</div>
        <div class="number"><?= $esc($invoiceNumber) ?></div>
        <div class="date"><?= $esc($invoiceDate) ?></div>
      </div>
    </div>

    <div class="gold-line"></div>

    <div class="inv-body">

      <div class="info-row">
        <div class="info-block">
          <h3>Order Details</h3>
          <p><strong><?= $esc($order['order_number']) ?></strong></p>
          <p>Placed on: <?= $esc($orderDate) ?></p>
          <p>Payment: <?= $esc(ucfirst((string) $order['payment_method'])) ?></p>
          <?php if (!empty($order['delivery_estimate_date'])): ?>
          <p>Est. Delivery: <?= $esc(date('d M Y', strtotime((string) $order['delivery_estimate_date']))) ?></p>
          <?php endif; ?>
        </div>
        <div class="info-block">
          <h3>Bill To</h3>
          <p>
            <strong><?= $esc($order['customer_name']) ?></strong><br>
            <?php if (!empty($order['customer_email'])): ?>
              <?= $esc($order['customer_email']) ?><br>
            <?php endif; ?>
            <?= $esc($order['customer_phone']) ?><br>
            <?= $esc($order['address_line1']) ?><?php if (!empty($order['address_line2'])): ?>, <?= $esc($order['address_line2']) ?><?php endif; ?><br>
            <?= $esc($order['city']) ?>, <?= $esc($order['state']) ?> – <?= $esc($order['pincode']) ?><br>
            India
          </p>
        </div>
      </div>

      <div class="status-row">
        <span class="pill <?= $esc($oPillClass) ?>">
          <span class="pill-dot"></span>
          Order: <?= $esc(ucfirst(str_replace('_', ' ', $oStatus))) ?>
        </span>
        <span class="pill <?= $esc($pPillClass) ?>">
          <span class="pill-dot"></span>
          Payment: <?= $esc(ucfirst(str_replace('_', ' ', $pStatus))) ?>
        </span>
      </div>

      <div class="items-label">Items Ordered</div>
      <table>
        <thead>
          <tr><th>Product</th><th>Qty</th><th>Unit Price</th><th>Amount</th></tr>
        </thead>
        <tbody>
          <?php foreach ($items as $item): ?>
          <tr>
            <td>
              <div class="product-thumb">
                <?php if (!empty($item['image_url'])): ?>
                  <img src="<?= $esc($item['image_url']) ?>" alt="<?= $esc($item['product_name']) ?>">
                <?php else: ?>
                  <div class="product-thumb-placeholder">🍬</div>
                <?php endif; ?>
                <div>
                  <div class="product-name"><?= $esc($item['product_name']) ?></div>
                  <div class="product-slug"><?= $esc($item['product_slug']) ?></div>
                </div>
              </div>
            </td>
            <td><?= (int) $item['quantity'] ?></td>
            <td><?= $inr((float) $item['unit_price']) ?></td>
            <td><?= $inr((float) $item['total_price']) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>

      <div class="totals-wrap">
        <table class="totals-table">
          <tr><td>Subtotal</td><td><?= $inr($subtotal) ?></td></tr>
          <tr>
            <td>Shipping</td>
            <td><?= $shippingAmount > 0 ? $inr($shippingAmount) : '<span style="color:#15803d">Free</span>' ?></td>
          </tr>
          <?php if ($discountAmount > 0): ?>
          <tr class="discount"><td>Discount</td><td>− <?= $inr($discountAmount) ?></td></tr>
          <?php endif; ?>
          <?php if ($taxAmount > 0): ?>
          <tr><td>Tax</td><td><?= $inr($taxAmount) ?></td></tr>
          <?php endif; ?>
          <tr class="grand"><td>Grand Total</td><td><?= $inr($totalAmount) ?></td></tr>
        </table>
      </div>

    </div>

    <div class="inv-footer">
      <p>Thank you for your order! &nbsp;·&nbsp; <a href="mailto:info@anshulfoodproduct.com">info@anshulfoodproduct.com</a></p>
      <p>© <?= date('Y') ?> Anshul Food Products, Nashik</p>
    </div>

  </div>
</body>
</html>
        <?php
        // phpcs:enable
        echo ob_get_clean();
        exit();
    }
}