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

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

if (!$sale_id || !$shop_id) {
    echo '<div class="alert alert-danger">Invalid request</div>';
    exit;
}

// Get sale details
$sale_sql = "SELECT s.*, c.name as customer_name, c.phone as customer_phone, 
                    c.email as customer_email, c.address as customer_address,
                    u.fullname as created_by_name,
                    COUNT(DISTINCT sl.id) as item_count,
                    SUM(sl.qty) as total_qty
             FROM sales s
             LEFT JOIN customers c ON s.customer_id = c.id
             LEFT JOIN users u ON s.created_by = u.id
             LEFT JOIN sale_lines sl ON s.id = sl.sale_id
             WHERE s.id = :id AND s.shop_id = :shop_id
             GROUP BY s.id";
             
$sale_stmt = $pdo->prepare($sale_sql);
$sale_stmt->execute([':id' => $sale_id, ':shop_id' => $shop_id]);
$sale = $sale_stmt->fetch(PDO::FETCH_ASSOC);

if (!$sale) {
    echo '<div class="alert alert-danger">Sale not found or you don\'t have permission to view it.</div>';
    exit;
}

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

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

$status_class = '';
switch ($sale['status']) {
    case 'paid': $status_class = 'badge-success'; break;
    case 'open': $status_class = 'badge-warning'; break;
    case 'partially_paid': $status_class = 'badge-info'; break;
    case 'cancelled': $status_class = 'badge-danger'; break;
}
?>

<div class="row">
    <div class="col-md-12">
        <!-- Sale Header -->
        <div class="card mb-3">
            <div class="card-header bg-light">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Sale #<?= htmlspecialchars($sale['invoice_no']) ?></h5>
                    <span class="badge <?= $status_class ?> badge-lg"><?= strtoupper(str_replace('_', ' ', $sale['status'])) ?></span>
                </div>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <table class="table table-sm table-borderless">
                            <tr>
                                <th width="120">Date:</th>
                                <td><?= date('d/m/Y H:i', strtotime($sale['sale_date'])) ?></td>
                            </tr>
                            <tr>
                                <th>Customer:</th>
                                <td>
                                    <?= $sale['customer_name'] ? htmlspecialchars($sale['customer_name']) : '<em>Walk-in Customer</em>' ?>
                                    <?php if ($sale['customer_phone']): ?>
                                    <br><small class="text-muted"><?= htmlspecialchars($sale['customer_phone']) ?></small>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Created by:</th>
                                <td><?= htmlspecialchars($sale['created_by_name'] ?? 'N/A') ?></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <table class="table table-sm table-borderless">
                            <tr>
                                <th width="120">Total Amount:</th>
                                <td class="text-success font-weight-bold">TZS <?= number_format($sale['total'], 2) ?></td>
                            </tr>
                            <tr>
                                <th>Amount Paid:</th>
                                <td class="text-primary">TZS <?= number_format($sale['paid'], 2) ?></td>
                            </tr>
                            <tr>
                                <th>Balance Due:</th>
                                <td class="text-danger">TZS <?= number_format(max(0, $sale['total'] - $sale['paid']), 2) ?></td>
                            </tr>
                            <tr>
                                <th>Items:</th>
                                <td><?= $sale['item_count'] ?> items (<?= $sale['total_qty'] ?> units)</td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Items Table -->
        <div class="card mb-3">
            <div class="card-header bg-light">
                <h6 class="mb-0">Items Sold</h6>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm table-bordered mb-0">
                        <thead class="thead-light">
                            <tr>
                                <th>#</th>
                                <th>Product</th>
                                <th>SKU</th>
                                <th>Batch No</th>
                                <th>Expiry</th>
                                <th class="text-center">Qty</th>
                                <th class="text-center">Unit</th>
                                <th class="text-right">Unit Price</th>
                                <th class="text-right">Discount</th>
                                <th class="text-right">Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($items as $index => $item): ?>
                            <tr>
                                <td><?= $index + 1 ?></td>
                                <td><?= htmlspecialchars($item['product_name']) ?></td>
                                <td><?= htmlspecialchars($item['sku']) ?></td>
                                <td><?= htmlspecialchars($item['batch_no'] ?? 'N/A') ?></td>
                                <td><?= $item['expiry_date'] ? date('m/Y', strtotime($item['expiry_date'])) : 'N/A' ?></td>
                                <td class="text-center"><?= $item['qty'] ?></td>
                                <td class="text-center"><?= htmlspecialchars($item['unit']) ?></td>
                                <td class="text-right">TZS <?= number_format($item['unit_price'], 2) ?></td>
                                <td class="text-right">TZS <?= number_format($item['discount'], 2) ?></td>
                                <td class="text-right font-weight-bold">TZS <?= number_format($item['line_total'], 2) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot class="bg-light">
                            <tr>
                                <td colspan="9" class="text-right font-weight-bold">Subtotal:</td>
                                <td class="text-right font-weight-bold">TZS <?= number_format($sale['total'], 2) ?></td>
                            </tr>
                            <?php if ($sale['total'] > $sale['paid']): ?>
                            <tr>
                                <td colspan="9" class="text-right font-weight-bold text-danger">Balance Due:</td>
                                <td class="text-right font-weight-bold text-danger">TZS <?= number_format($sale['total'] - $sale['paid'], 2) ?></td>
                            </tr>
                            <?php endif; ?>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>

        <!-- Payments -->
        <?php if (!empty($payments)): ?>
        <div class="card">
            <div class="card-header bg-light">
                <h6 class="mb-0">Payment History</h6>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-sm table-bordered mb-0">
                        <thead class="thead-light">
                            <tr>
                                <th>#</th>
                                <th>Date & Time</th>
                                <th>Method</th>
                                <th>Amount</th>
                                <th>Received by</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($payments as $index => $payment): ?>
                            <tr>
                                <td><?= $index + 1 ?></td>
                                <td><?= date('d/m/Y H:i', strtotime($payment['paid_at'])) ?></td>
                                <td><span class="badge payment-<?= $payment['method'] ?>"><?= $payment['method'] ?></span></td>
                                <td class="text-success text-right">TZS <?= number_format($payment['amount'], 2) ?></td>
                                <td>User #<?= $payment['created_by'] ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>