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


if (!isset($_SESSION['user']['id'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

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

// Get all purchases for this product
$sql = "SELECT 
            pu.id,
            pu.invoice_no,
            pu.purchase_date,
            pu.total,
            pl.qty,
            pl.cost_price,
            (pl.qty * pl.cost_price) as line_total,
            s.name as supplier_name,
            u.fullname as created_by_name
        FROM purchases pu
        JOIN purchase_lines pl ON pu.id = pl.purchase_id
        JOIN product_batches pb ON pl.batch_id = pb.id
        LEFT JOIN suppliers s ON pu.supplier_id = s.id
        LEFT JOIN users u ON pu.created_by = u.id
        WHERE pb.product_id = ?
        AND pu.shop_id = ?
        ORDER BY pu.purchase_date DESC
        LIMIT 50";

$stmt = $pdo->prepare($sql);
$stmt->execute([$product_id, $shop_id]);
$purchases = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get product name
$product_sql = "SELECT name FROM products WHERE id = ?";
$product_stmt = $pdo->prepare($product_sql);
$product_stmt->execute([$product_id]);
$product = $product_stmt->fetch(PDO::FETCH_ASSOC);
$product_name = $product['name'] ?? 'Product #' . $product_id;
?>

<div class="container-fluid">
    <h4 class="text-primary mb-3">
        <i class="fas fa-shopping-cart"></i> Purchase History for: <?= htmlspecialchars($product_name) ?>
    </h4>
    
    <?php if(empty($purchases)): ?>
    <div class="alert alert-info">
        <i class="fas fa-info-circle"></i> No purchase history found for this product.
    </div>
    <?php else: ?>
    <div class="table-responsive">
        <table class="table table-bordered table-hover">
            <thead class="thead-dark">
                <tr>
                    <th>#</th>
                    <th>Invoice No</th>
                    <th>Date</th>
                    <th>Quantity</th>
                    <th>Cost Price</th>
                    <th>Line Total</th>
                    <th>Supplier</th>
                    <th>Created By</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $total_qty = 0;
                $total_value = 0;
                foreach($purchases as $index => $purchase): 
                    $total_qty += $purchase['qty'];
                    $total_value += $purchase['line_total'];
                ?>
                <tr>
                    <td><?= $index + 1 ?></td>
                    <td><strong><?= htmlspecialchars($purchase['invoice_no']) ?></strong></td>
                    <td><?= date('M d, Y', strtotime($purchase['purchase_date'])) ?></td>
                    <td class="text-center"><?= $purchase['qty'] ?></td>
                    <td class="text-right"><?= number_format($purchase['cost_price'], 2) ?></td>
                    <td class="text-right"><?= number_format($purchase['line_total'], 2) ?></td>
                    <td><?= htmlspecialchars($purchase['supplier_name'] ?? 'N/A') ?></td>
                    <td><?= htmlspecialchars($purchase['created_by_name'] ?? 'System') ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot class="bg-light">
                <tr>
                    <td colspan="3" class="text-right"><strong>Totals:</strong></td>
                    <td class="text-center"><strong><?= $total_qty ?></strong></td>
                    <td></td>
                    <td class="text-right"><strong><?= number_format($total_value, 2) ?></strong></td>
                    <td colspan="2"></td>
                </tr>
            </tfoot>
        </table>
    </div>
    <div class="mt-3">
        <p class="text-muted">
            <small>Showing <?= count($purchases) ?> purchase records</small>
        </p>
    </div>
    <?php endif; ?>
    
    <div class="mt-4 text-center">
        <button class="btn btn-secondary" onclick="Swal.close()">
            <i class="fas fa-times"></i> Close
        </button>
    </div>
</div>