<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('purchase_management');

$pdo = getDB();
$id = (int)($_GET['id'] ?? 0);
if (!$id) { $_SESSION['error'] = 'Invalid purchase ID.'; header('Location: purchases.php'); exit; }

$stmt = $pdo->prepare("SELECT p.*, s.supplier_name, s.company_name, s.contact_person, s.phone as supplier_phone, s.email as supplier_email, s.address as supplier_address, u.name 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 = ?");
$stmt->execute([$id]);
$purchase = $stmt->fetch();
if (!$purchase) { $_SESSION['error'] = 'Purchase not found.'; header('Location: purchases.php'); exit; }

$items = $pdo->prepare("SELECT pi.*, p.product_code, p.product_name, p.product_type FROM purchase_items pi JOIN products p ON pi.product_id = p.id WHERE pi.purchase_id = ? ORDER BY pi.id");
$items->execute([$id]);
$items_list = $items->fetchAll();

$payments = $pdo->prepare("SELECT * FROM payments WHERE reference_id = ? AND payment_type = 'supplier' ORDER BY payment_date DESC");
$payments->execute([$id]);
$payment_info = $payments->fetch();

$imeis = $pdo->prepare("SELECT pi.*, pii.product_id, pii.id as purchase_item_id FROM product_imei pi JOIN purchase_items pii ON pi.purchase_item_id = pii.id WHERE pii.purchase_id = ? ORDER BY pi.id");
$imeis->execute([$id]);
$imei_list = $imeis->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-file-invoice me-2"></i>Purchase Invoice</h4>
            <div>
                <a href="purchases.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
                <a href="print_purchase.php?id=<?= $id ?>" class="btn btn-outline-info" target="_blank"><i class="fas fa-print me-1"></i>Print</a>
                <?php if ($purchase['purchase_status'] === 'Pending'): ?>
                <a href="add_purchase.php?edit=<?= $id ?>" class="btn btn-warning"><i class="fas fa-edit me-1"></i>Edit</a>
                <?php endif; ?>
                <?php if ($purchase['purchase_status'] !== 'Cancelled'): ?>
                <form method="POST" action="purchases.php" style="display:inline;" onsubmit="return confirm('Cancel this purchase?');">
                    <input type="hidden" name="action" value="cancel_purchase">
                    <input type="hidden" name="purchase_id" value="<?= $id ?>">
                    <button type="submit" class="btn btn-danger"><i class="fas fa-ban me-1"></i>Cancel</button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h5 class="fw-bold"><?= htmlspecialchars($purchase['purchase_no']) ?></h5>
                        <p class="mb-1"><strong>Status:</strong> <?= getStatusBadge($purchase['purchase_status']) ?></p>
                        <p class="mb-1"><strong>Date:</strong> <?= formatDate($purchase['purchase_date']) ?></p>
                        <p class="mb-1"><strong>Created By:</strong> <?= htmlspecialchars($purchase['created_by_name'] ?? '-') ?></p>
                        <p class="mb-0"><strong>Note:</strong> <?= htmlspecialchars($purchase['note'] ?? '-') ?></p>
                    </div>
                    <div class="col-md-6 text-md-end">
                        <h6 class="fw-bold">Supplier Information</h6>
                        <p class="mb-1"><strong><?= htmlspecialchars($purchase['supplier_name']) ?></strong></p>
                        <?php if ($purchase['company_name']): ?><p class="mb-1"><?= htmlspecialchars($purchase['company_name']) ?></p><?php endif; ?>
                        <p class="mb-1"><?= htmlspecialchars($purchase['contact_person'] ?? '') ?></p>
                        <p class="mb-1"><?= htmlspecialchars($purchase['supplier_phone'] ?? '') ?></p>
                        <p class="mb-0"><?= htmlspecialchars($purchase['supplier_address'] ?? '') ?></p>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header"><i class="fas fa-boxes me-2"></i>Purchase Items</div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered no-datatable">
                        <thead><tr><th>#</th><th>Code</th><th>Product Name</th><th>Type</th><th>Quantity</th><th>Cost Price</th><th>Selling Price</th><th>Total</th></tr></thead>
                        <tbody>
                            <?php $i = 1; $total_qty = 0; ?>
                            <?php foreach ($items_list as $item): ?>
                            <?php $total_qty += $item['quantity']; ?>
                            <tr>
                                <td><?= $i++ ?></td>
                                <td><code><?= htmlspecialchars($item['product_code']) ?></code></td>
                                <td><?= htmlspecialchars($item['product_name']) ?></td>
                                <td><span class="badge bg-secondary"><?= htmlspecialchars(ucfirst($item['product_type'] ?? 'N/A')) ?></span></td>
                                <td><?= (int)$item['quantity'] ?></td>
                                <td><?= formatCurrency($item['cost_price']) ?></td>
                                <td><?= formatCurrency($item['selling_price']) ?></td>
                                <td><strong><?= formatCurrency($item['total_price']) ?></strong></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr class="fw-bold">
                                <td colspan="4" class="text-end">Total (<?= $total_qty ?> items)</td>
                                <td><?= $total_qty ?></td>
                                <td colspan="2"></td>
                                <td><?= formatCurrency($purchase['total_amount']) ?></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>

        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card h-100">
                    <div class="card-header"><i class="fas fa-calculator me-2"></i>Summary</div>
                    <div class="card-body">
                        <table class="table table-sm table-borderless">
                            <tr><td>Subtotal</td><td class="text-end"><?= formatCurrency($purchase['subtotal']) ?></td></tr>
                            <tr><td>Discount</td><td class="text-end text-danger">- <?= formatCurrency($purchase['discount']) ?></td></tr>
                            <tr><td>Tax</td><td class="text-end">+ <?= formatCurrency($purchase['tax']) ?></td></tr>
                            <tr class="fw-bold"><td>Total Amount</td><td class="text-end"><?= formatCurrency($purchase['total_amount']) ?></td></tr>
                            <tr><td>Paid Amount</td><td class="text-end text-success"><?= formatCurrency($purchase['paid_amount']) ?></td></tr>
                            <tr class="fw-bold <?= $purchase['due_amount'] > 0 ? 'text-danger' : 'text-success' ?>"><td>Due Amount</td><td class="text-end"><?= formatCurrency($purchase['due_amount']) ?></td></tr>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card h-100">
                    <div class="card-header"><i class="fas fa-money-bill me-2"></i>Payment Info</div>
                    <div class="card-body">
                        <table class="table table-sm table-borderless">
                            <tr><td>Payment Method</td><td class="text-end"><?= htmlspecialchars($purchase['payment_method']) ?></td></tr>
                            <?php if ($payment_info): ?>
                            <tr><td>Payment No</td><td class="text-end"><code><?= htmlspecialchars($payment_info['payment_no'] ?? '-') ?></code></td></tr>
                            <tr><td>Payment Date</td><td class="text-end"><?= formatDateTime($payment_info['payment_date']) ?></td></tr>
                            <tr><td>Payment Note</td><td class="text-end"><?= htmlspecialchars($payment_info['note'] ?? '-') ?></td></tr>
                            <?php endif; ?>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <?php if (!empty($imei_list)): ?>
        <div class="card mb-4">
            <div class="card-header"><i class="fas fa-microchip me-2"></i>IMEI Records</div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="purchaseImeiTable" class="table table-sm table-hover datatable">
                        <thead><tr><th>#</th><th>Product</th><th>IMEI Number</th><th>Serial Number</th><th>Status</th></tr></thead>
                        <tbody>
                            <?php $j = 1; foreach ($imei_list as $imei): ?>
                            <?php
                            $prod_name = '';
                            foreach ($items_list as $it) {
                                if ($it['purchase_item_id'] == $imei['purchase_item_id'] || $it['product_id'] == $imei['product_id']) {
                                    $prod_name = $it['product_name'];
                                    break;
                                }
                            }
                            ?>
                            <tr>
                                <td><?= $j++ ?></td>
                                <td><?= htmlspecialchars($prod_name) ?></td>
                                <td><code><?= htmlspecialchars($imei['imei_number']) ?></code></td>
                                <td><?= htmlspecialchars($imei['serial_number'] ?? '-') ?></td>
                                <td><?= getStatusBadge($imei['status']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
