<?php
// modules/sales/view_sale.php
session_start();
require_once '../assets/db_connect.php';

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

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

// Get sale details
$sql = "SELECT s.*, 
               c.name as customer_name,
               c.phone as customer_phone,
               c.address as customer_address,
               u.fullname 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 = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$sale_id]);
$sale = $stmt->fetch(PDO::FETCH_ASSOC);

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

// Get sale items
$items_sql = "SELECT sl.*, 
                     p.name as product_name,
                     p.sku as product_sku,
                     pb.batch_no
              FROM sale_lines sl
              LEFT JOIN products p ON sl.product_id = p.id
              LEFT JOIN product_batches pb ON sl.batch_id = pb.id
              WHERE sl.sale_id = ?
              ORDER BY sl.id";
$items_stmt = $pdo->prepare($items_sql);
$items_stmt->execute([$sale_id]);
$items = $items_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get payments
$payments_sql = "SELECT * FROM payments WHERE sale_id = ? ORDER BY paid_at";
$payments_stmt = $pdo->prepare($payments_sql);
$payments_stmt->execute([$sale_id]);
$payments = $payments_stmt->fetchAll(PDO::FETCH_ASSOC);

$due = $sale['total'] - $sale['paid'];
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <!-- Sale Header -->
            <div class="card mb-3">
                <div class="card-header bg-primary text-white d-flex justify-content-between">
                    <h5 class="mb-0">Invoice: <?= htmlspecialchars($sale['invoice_no']) ?></h5>
                    <span class="badge badge-light"><?= date('d/m/Y H:i', strtotime($sale['sale_date'])) ?></span>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Customer Information</h6>
                            <p class="mb-1">
                                <strong>Name:</strong> 
                                <?= $sale['customer_name'] ? htmlspecialchars($sale['customer_name']) : 'Walk-in Customer' ?>
                            </p>
                            <?php if ($sale['customer_phone']): ?>
                                <p class="mb-1"><strong>Phone:</strong> <?= htmlspecialchars($sale['customer_phone']) ?></p>
                            <?php endif; ?>
                            <?php if ($sale['customer_address']): ?>
                                <p class="mb-1"><strong>Address:</strong> <?= htmlspecialchars($sale['customer_address']) ?></p>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-6 text-right">
                            <h6>Sale Information</h6>
                            <p class="mb-1"><strong>Created by:</strong> <?= htmlspecialchars($sale['created_by_name']) ?></p>
                            <p class="mb-1">
                                <strong>Status:</strong> 
                                <span class="badge status-<?= $sale['status'] ?>">
                                    <?= ucfirst($sale['status']) ?>
                                </span>
                            </p>
                            <p class="mb-1"><strong>Total Items:</strong> <?= count($items) ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Items Table -->
            <div class="card mb-3">
                <div class="card-header bg-light">
                    <h5 class="mb-0">Items Sold</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-bordered mb-0">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Product</th>
                                    <th>SKU</th>
                                    <th>Batch</th>
                                    <th class="text-center">Qty</th>
                                    <th class="text-right">Price</th>
                                    <th class="text-right">Discount</th>
                                    <th class="text-right">Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $subtotal = 0; ?>
                                <?php foreach ($items as $index => $item): ?>
                                    <?php 
                                    $line_total = $item['qty'] * $item['unit_price'];
                                    $discount_amount = $line_total * ($item['discount'] / 100);
                                    $item_total = $line_total - $discount_amount;
                                    $subtotal += $item_total;
                                    ?>
                                    <tr>
                                        <td><?= $index + 1 ?></td>
                                        <td><?= htmlspecialchars($item['product_name']) ?></td>
                                        <td><?= htmlspecialchars($item['product_sku'] ?? 'N/A') ?></td>
                                        <td><?= htmlspecialchars($item['batch_no'] ?? 'N/A') ?></td>
                                        <td class="text-center"><?= $item['qty'] ?></td>
                                        <td class="text-right"><?= number_format($item['unit_price'], 2) ?></td>
                                        <td class="text-right"><?= number_format($item['discount'], 2) ?>%</td>
                                        <td class="text-right"><?= number_format($item_total, 2) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (empty($items)): ?>
                                    <tr>
                                        <td colspan="8" class="text-center text-muted">No items found</td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Summary -->
            <div class="row">
                <div class="col-md-6">
                    <!-- Payments -->
                    <div class="card mb-3">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Payments</h5>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-bordered mb-0">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Method</th>
                                            <th class="text-right">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($payments as $payment): ?>
                                            <tr>
                                                <td><?= date('d/m/Y H:i', strtotime($payment['paid_at'])) ?></td>
                                                <td><?= $payment['method'] ?></td>
                                                <td class="text-right"><?= number_format($payment['amount'], 2) ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                        <?php if (empty($payments)): ?>
                                            <tr>
                                                <td colspan="3" class="text-center text-muted">No payments recorded</td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <!-- Totals -->
                    <div class="card mb-3">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Summary</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-borderless">
                                <tr>
                                    <td><strong>Subtotal:</strong></td>
                                    <td class="text-right"><?= number_format($subtotal, 2) ?></td>
                                </tr>
                                <tr>
                                    <td><strong>Tax/VAT:</strong></td>
                                    <td class="text-right"><?= number_format($sale['total'] - $subtotal, 2) ?></td>
                                </tr>
                                <tr class="table-active">
                                    <td><strong>Total Amount:</strong></td>
                                    <td class="text-right"><strong><?= number_format($sale['total'], 2) ?></strong></td>
                                </tr>
                                <tr class="table-success">
                                    <td><strong>Total Paid:</strong></td>
                                    <td class="text-right"><strong class="text-success"><?= number_format($sale['paid'], 2) ?></strong></td>
                                </tr>
                                <tr class="table-<?= $due > 0 ? 'danger' : 'success' ?>">
                                    <td><strong>Balance Due:</strong></td>
                                    <td class="text-right"><strong class="text-<?= $due > 0 ? 'danger' : 'success' ?>"><?= number_format($due, 2) ?></strong></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="text-center mt-3">
                <button type="button" class="btn btn-primary" onclick="printReceipt(<?= $sale_id ?>)">
                    <i class="fas fa-print"></i> Print Receipt
                </button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>