<?php
session_start();
require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

if (!isset($_SESSION['user']['shop_id'])) {
    echo "<div class='alert alert-danger'>Shop session missing.</div>";
    exit;
}

$shop_id = $_SESSION['user']['shop_id'];
$sale_id = intval($_GET['id'] ?? 0);

if ($sale_id == 0) {
    echo "<div class='alert alert-danger'>Sale ID missing.</div>";
    exit;
}

/* --------------------------------------------------------
   FETCH SALE (But only if it belongs to this SHOP)
---------------------------------------------------------*/
$stmt = $pdo->prepare("
    SELECT s.*, 
           c.name AS customer_name,
           u.username AS created_by_name
    FROM sales s
    LEFT JOIN customers c ON s.customer_id = c.id
    LEFT JOIN users u ON s.created_by = u.id
    WHERE s.id = ? AND s.shop_id = ?
");
$stmt->execute([$sale_id, $shop_id]);
$sale = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$sale) {
    echo "<div class='alert alert-danger'>Sale not found or not accessible.</div>";
    exit;
}

/* --------------------------------------------------------
   FETCH LINE ITEMS (Correct join: sale_lines ? product_batches ? products)
---------------------------------------------------------*/
$stmt_items = $pdo->prepare("
    SELECT sl.*, 
           pb.batch_no,
           p.name AS product_name
    FROM sale_lines sl
    LEFT JOIN product_batches pb ON sl.batch_id = pb.id
    LEFT JOIN products p ON pb.product_id = p.id
    WHERE sl.sale_id = ?
");
$stmt_items->execute([$sale_id]);
$items = $stmt_items->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">

    <div class="d-flex justify-content-between mb-3">
        <h3 class="text-success">View Sale</h3>
        <a href="list_sales.php" class="btn btn-secondary">? Back to Sales</a>
    </div>

    <!-- SALE SUMMARY CARD -->
    <div class="card mb-4">
        <div class="card-header bg-success text-white">
            <strong>Sale Summary</strong>
        </div>

        <div class="card-body">
            <div class="row mb-2">
                <div class="col-md-4"><strong>Invoice:</strong> <?= htmlspecialchars($sale['invoice_no']) ?></div>
                <div class="col-md-4"><strong>Date:</strong> <?= date('d-M-Y H:i', strtotime($sale['sale_date'])) ?></div>
                <div class="col-md-4"><strong>Status:</strong> <?= htmlspecialchars($sale['status']) ?></div>
            </div>

            <div class="row mb-2">
                <div class="col-md-4"><strong>Customer:</strong> <?= htmlspecialchars($sale['customer_name'] ?? '-') ?></div>
                <div class="col-md-4"><strong>Created By:</strong> <?= htmlspecialchars($sale['created_by_name'] ?? '-') ?></div>
            </div>

            <div class="row">
                <div class="col-md-4"><strong>Total:</strong> <?= number_format($sale['total'], 2) ?></div>
                <div class="col-md-4"><strong>Paid:</strong> <?= number_format($sale['paid'], 2) ?></div>
                <div class="col-md-4">
                    <strong>Balance:</strong>
                    <?= number_format($sale['total'] - $sale['paid'], 2) ?>
                </div>
            </div>
        </div>
    </div>

    <!-- LINE ITEMS -->
    <div class="card">
        <div class="card-header bg-light">
            <strong>Sale Items</strong>
        </div>

        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-bordered table-hover mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>#</th>
                            <th>Product</th>
                            <th>Batch</th>
                            <th>Qty</th>
                            <th>Unit Price</th>
                            <th>Discount</th>
                            <th>Line Total</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $i = 1;
                        foreach ($items as $it): ?>
                        <tr>
                            <td><?= $i++ ?></td>
                            <td><?= htmlspecialchars($it['product_name']) ?></td>
                            <td><?= htmlspecialchars($it['batch_no']) ?></td>
                            <td><?= $it['qty'] ?></td>
                            <td><?= number_format($it['unit_price'], 2) ?></td>
                            <td><?= number_format($it['discount'], 2) ?></td>
                            <td><?= number_format($it['line_total'], 2) ?></td>
                        </tr>
                        <?php endforeach; ?>

                        <?php if (count($items) === 0): ?>
                        <tr><td colspan="7" class="text-center">No items found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- ACTION BUTTONS -->
    <div class="mt-3">
        <a href="print_invoice.php?id=<?= $sale_id ?>" target="_blank" class="btn btn-primary">?? Print Invoice</a>
        <a href="edit_sale.php?id=<?= $sale_id ?>" class="btn btn-warning">? Edit Sale</a>
    </div>

</div>

<?php require_once '../includes/footer.php'; ?>
