<?php
session_start();
include 'db.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    die('Unauthorized access');
}

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

if (!$purchase_id) {
    die('Invalid purchase ID');
}

try {
    // Get purchase header with supplier information
    $purchase_stmt = $conn->prepare("
        SELECT 
            p.*,
            v.name AS supplier_name,
            v.contact_number,
            v.email,
            v.address
        FROM purchases p
        JOIN vendors v ON p.vendor_id = v.id
        WHERE p.id = ?
    ");
    $purchase_stmt->bind_param("i", $purchase_id);
    $purchase_stmt->execute();
    $purchase = $purchase_stmt->get_result()->fetch_assoc();
    
    if (!$purchase) {
        die('Purchase not found');
    }
    
    // Get purchase items
    $items_stmt = $conn->prepare("
        SELECT 
            pi.*,
            i.item_code
        FROM purchase_items pi
        LEFT JOIN items i ON pi.item_id = i.id
        WHERE pi.purchase_id = ? 
        ORDER BY pi.id
    ");
    $items_stmt->bind_param("i", $purchase_id);
    $items_stmt->execute();
    $items_result = $items_stmt->get_result();
    
    $items = [];
    while ($item = $items_result->fetch_assoc()) {
        $items[] = $item;
    }
    
} catch (Exception $e) {
    die('Error fetching purchase details: ' . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Purchase #<?= htmlspecialchars($purchase['purchase_number']) ?></title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            color: #333;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #007bff;
            padding-bottom: 20px;
        }
        .company-name {
            font-size: 24px;
            font-weight: bold;
            color: #007bff;
            margin-bottom: 10px;
        }
        .purchase-title {
            font-size: 18px;
            color: #666;
        }
        .info-section {
            margin-bottom: 20px;
        }
        .info-row {
            display: flex;
            margin-bottom: 8px;
        }
        .info-label {
            font-weight: bold;
            width: 150px;
        }
        .info-value {
            flex: 1;
        }
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .items-table th,
        .items-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .items-table th {
            background-color: #007bff;
            color: white;
        }
        .items-table .text-center {
            text-align: center;
        }
        .items-table .text-right {
            text-align: right;
        }
        .totals-section {
            margin-top: 20px;
            text-align: right;
        }
        .total-row {
            margin-bottom: 5px;
        }
        .total-label {
            font-weight: bold;
            display: inline-block;
            width: 150px;
        }
        .total-value {
            display: inline-block;
            width: 100px;
        }
        .final-total {
            border-top: 2px solid #007bff;
            padding-top: 10px;
            font-size: 16px;
            font-weight: bold;
        }
        @media print {
            body { margin: 0; }
            .no-print { display: none; }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="company-name">ITR POS System</div>
        <div class="purchase-title">Purchase Order Details</div>
    </div>

    <div class="info-section">
        <div class="info-row">
            <div class="info-label">Purchase #:</div>
            <div class="info-value"><?= htmlspecialchars($purchase['purchase_number']) ?></div>
        </div>
        <div class="info-row">
            <div class="info-label">Date:</div>
            <div class="info-value"><?= date('M d, Y H:i', strtotime($purchase['purchase_date'])) ?></div>
        </div>
        <div class="info-row">
            <div class="info-label">Supplier:</div>
            <div class="info-value"><?= htmlspecialchars($purchase['supplier_name']) ?></div>
        </div>
        <div class="info-row">
            <div class="info-label">Status:</div>
            <div class="info-value"><?= ucfirst($purchase['status']) ?></div>
        </div>
        <div class="info-row">
            <div class="info-label">Payment Method:</div>
            <div class="info-value"><?= ucfirst($purchase['payment_method']) ?></div>
        </div>
    </div>

    <table class="items-table">
        <thead>
            <tr>
                <th>Item Name</th>
                <th>Item Code</th>
                <th class="text-center">Qty</th>
                <th class="text-right">Unit Cost</th>
                <th class="text-right">Tax Rate</th>
                <th class="text-right">Total Cost</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $subtotal = 0;
            foreach ($items as $item): 
                $item_total = $item['quantity'] * $item['unit_cost'];
                $subtotal += $item_total;
            ?>
            <tr>
                <td><?= htmlspecialchars($item['item_name']) ?></td>
                <td><?= htmlspecialchars($item['item_code'] ?? 'N/A') ?></td>
                <td class="text-center"><?= $item['quantity'] ?></td>
                <td class="text-right">Rs <?= number_format($item['unit_cost'], 2) ?></td>
                <td class="text-right"><?= number_format($item['tax_rate'], 2) ?>%</td>
                <td class="text-right">Rs <?= number_format($item_total, 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div class="totals-section">
        <div class="total-row">
            <span class="total-label">Subtotal:</span>
            <span class="total-value">Rs <?= number_format($subtotal, 2) ?></span>
        </div>
        <div class="total-row">
            <span class="total-label">Tax Amount:</span>
            <span class="total-value">Rs <?= number_format($purchase['tax_amount'], 2) ?></span>
        </div>
        <?php if ($purchase['discount_amount'] > 0): ?>
        <div class="total-row">
            <span class="total-label">Discount:</span>
            <span class="total-value">-Rs <?= number_format($purchase['discount_amount'], 2) ?></span>
        </div>
        <?php endif; ?>
        <div class="total-row final-total">
            <span class="total-label">Net Total:</span>
            <span class="total-value">Rs <?= number_format($purchase['net_amount'], 2) ?></span>
        </div>
    </div>

    <div class="no-print" style="margin-top: 30px; text-align: center;">
        <button onclick="window.print()" style="background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">
            Print Purchase Order
        </button>
        <button onclick="window.close()" style="background-color: #6c757d; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin-left: 10px;">
            Close
        </button>
    </div>

    <script>
        // Auto-print when page loads
        window.onload = function() {
            setTimeout(function() {
                window.print();
            }, 500);
        };
    </script>
</body>
</html>
