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

// Check if user is logged in
if (!isset($_SESSION['user']['id']) || !isset($_SESSION['user']['shop_id'])) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'><div class='alert alert-danger'>Access denied. Please login.</div></div>";
    require_once '../includes/footer.php';
    exit();
}

$shop_id = $_SESSION['user']['shop_id'];
$user_id = $_SESSION['user']['id'];

// Validate purchase ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'>
            <div class='alert alert-danger'>Invalid purchase ID.</div>
            <a href='list_purchases.php' class='btn btn-secondary'>Back to Purchases</a>
          </div>";
    require_once '../includes/footer.php';
    exit();
}

$purchase_id = intval($_GET['id']);

// Fetch purchase
$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.id = ? AND p.shop_id = ?
");
$stmt->execute([$purchase_id, $shop_id]);
$purchase = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$purchase) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'>
            <div class='alert alert-danger'>Purchase not found.</div>
            <a href='list_purchases.php' class='btn btn-secondary'>Back to Purchases</a>
          </div>";
    require_once '../includes/footer.php';
    exit();
}

// Fetch line items
$stmtLines = $pdo->prepare("
    SELECT pl.*, 
           (pl.qty * pl.cost_price) AS line_total,
           pb.batch_no,
           pb.expiry_date,
           p.name AS product_name
    FROM purchase_lines pl
    LEFT JOIN product_batches pb ON pl.batch_id = pb.id
    LEFT JOIN products p ON pb.product_id = p.id
    WHERE pl.purchase_id = ?
");
$stmtLines->execute([$purchase_id]);
$lines = $stmtLines->fetchAll(PDO::FETCH_ASSOC);

// Calculate totals
$total_items = count($lines);
$total_qty = 0;
$total_cost = 0;
foreach ($lines as $line) {
    $total_qty += $line['qty'];
    $total_cost += $line['line_total'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View Purchase #<?= $purchase_id ?></title>
    <style>
        @media print {
            .sidebar, .navbar, .footer, .no-print, .btn, .alert {
                display: none !important;
            }
            .col-md-10 {
                width: 100% !important;
                margin: 0 !important;
                padding: 0 !important;
            }
            .print-title {
                text-align: center !important;
                margin-top: 0 !important;
                font-size: 22px !important;
                font-weight: bold !important;
            }
            .print-box {
                border: 1px solid black !important;
                padding: 12px !important;
            }
            table {
                width: 100% !important;
                border-collapse: collapse !important;
            }
            table th, table td {
                border: 1px solid black !important;
                padding: 6px !important;
                font-size: 14px !important;
            }
            tr {
                page-break-inside: avoid !important;
            }
        }
    </style>
</head>
<body>
<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 print-title">View Purchase #<?= $purchase['id'] ?></h3>
        <button class="btn btn-primary no-print" onclick="window.print()">Print</button>
    </div>

    <div class="card mb-4 print-box">
        <div class="card-body">
            <p><strong>Supplier:</strong> <?= htmlspecialchars($purchase['supplier_name']) ?></p>
            <p><strong>Invoice No:</strong> <?= htmlspecialchars($purchase['invoice_no']) ?></p>
            <p><strong>Date:</strong> <?= date('d-M-Y', strtotime($purchase['purchase_date'])) ?></p>
            <p><strong>Total:</strong> 
                <span class="badge badge-success">
                    <?= number_format($purchase['total'], 2) ?>
                </span>
            </p>
            <p><strong>Created By:</strong> <?= htmlspecialchars($purchase['created_by_name']) ?></p>
            <p><strong>Total Items:</strong> <?= $total_items ?></p>
            <p><strong>Total Quantity:</strong> <?= $total_qty ?></p>
        </div>
    </div>

    <h5 class="mb-3">Purchase Items</h5>

    <table class="table table-bordered">
        <thead>
            <tr>
                <th>#</th>
                <th>Product</th>
                <th>Batch No</th>
                <th>Expiry</th>
                <th>Qty</th>
                <th>Cost Price</th>
                <th>Line Total</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($lines)): ?>
                <tr><td colspan="7" class="text-center text-muted">No items found.</td></tr>
            <?php else: 
                $counter = 1;
                foreach ($lines as $line): ?>
                <tr>
                    <td><?= $counter++ ?></td>
                    <td><?= htmlspecialchars($line['product_name']) ?></td>
                    <td><?= htmlspecialchars($line['batch_no']) ?></td>
                    <td><?= $line['expiry_date'] ? date('d-M-Y', strtotime($line['expiry_date'])) : '-' ?></td>
                    <td><?= $line['qty'] ?></td>
                    <td><?= number_format($line['cost_price'], 2) ?></td>
                    <td><?= number_format($line['line_total'], 2) ?></td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            <tr class="table-info">
                <td colspan="4" class="text-right font-weight-bold">Totals:</td>
                <td class="font-weight-bold"><?= $total_qty ?></td>
                <td></td>
                <td class="font-weight-bold"><?= number_format($total_cost, 2) ?></td>
            </tr>
        </tbody>
    </table>

    <div class="mt-3 no-print">
        <a href="list_purchases.php" class="btn btn-secondary">Back to Purchases</a>
        <a href="edit_purchase.php?id=<?= $purchase_id ?>" class="btn btn-warning">Edit</a>
        <button class="btn btn-danger" onclick="deletePurchase(<?= $purchase_id ?>)">Delete</button>
    </div>

</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function deletePurchase(purchaseId) {
    if (confirm("Are you sure you want to delete purchase #" + purchaseId + "?")) {
        $.ajax({
            url: 'delete_purchase.php',
            type: 'POST',
            data: { id: purchaseId, user_id: <?= $user_id ?> },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    alert(response.message);
                    window.location.href = 'list_purchases.php';
                } else {
                    alert(response.message);
                }
            },
            error: function() {
                alert("An error occurred while deleting the purchase.");
            }
        });
    }
}

// Keyboard shortcuts
$(document).on('keydown', function(e) {
    if (e.ctrlKey && e.key === 'p') {
        e.preventDefault();
        window.print();
    }
    if (e.key === 'Escape') {
        window.location.href = 'list_purchases.php';
    }
});
</script>

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