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

// Ensure user is logged in
if (!isset($_SESSION['user']['id']) || !isset($_SESSION['user']['shop_id'])) {
    header("Location: ../../auth/login.php");
    exit();
}

$current_shop = $_SESSION['user']['shop_id'];
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="text-success">Purchases</h3>
        <a href="add_purchase.php" class="btn btn-primary">+ Add Purchase</a>
    </div>

    <div class="table-responsive">
        <table class="table table-bordered table-hover">
            <thead class="thead-light">
                <tr>
                    <th>ID</th>
                    <th>Supplier</th>
                    <th>Invoice No</th>
                    <th>Purchase Date</th>
                    <th>Total</th>
                    <th>Created By</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $stmt = $pdo->prepare("
                    SELECT p.*, s.name AS supplier_name, u.username AS created_by_name
                    FROM purchases p
                    LEFT JOIN suppliers s ON p.supplier_id = s.id
                    LEFT JOIN users u ON p.created_by = u.id
                    WHERE p.shop_id = ?
                    ORDER BY p.id DESC
                ");
                $stmt->execute([$current_shop]);

                while ($row = $stmt->fetch()):
                    // Ensure total is safely formatted (avoid null warning)
                    $total = isset($row['total']) ? (float)$row['total'] : 0;
                ?>
                <tr id="row-<?= $row['id'] ?>">
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['supplier_name'] ?? '-') ?></td>
                    <td><?= htmlspecialchars($row['invoice_no']) ?></td>
                    <td><?= $row['purchase_date'] ? date('d-M-Y', strtotime($row['purchase_date'])) : '-' ?></td>
                    <td><?= number_format($total, 2) ?></td>
                    <td><?= htmlspecialchars($row['created_by_name'] ?? '-') ?></td>
                    <td>
                        <a href="view_purchase.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-info">View</a>
                        <a href="edit_purchase.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-warning">Edit</a>
                        <button class="btn btn-sm btn-danger" onclick="deletePurchase(<?= $row['id'] ?>)">Delete</button>
                    </td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

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

<script>
// Delete purchase via AJAX
function deletePurchase(purchaseId) {
    if (confirm("Are you sure you want to delete this purchase? This will remove all related purchase lines.")) {
        $.ajax({
            url: 'delete_purchase.php',
            type: 'POST',
            data: { id: purchaseId },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    $("#row-" + purchaseId).fadeOut(400, function(){ $(this).remove(); });
                    alert(response.message);
                } else {
                    alert(response.message);
                }
            },
            error: function(xhr, status, error) {
                console.error("AJAX Error:", error);
                alert("An error occurred while deleting the purchase.");
            }
        });
    }
}
</script>
