<?php
require_once __DIR__ . '/../config/config.php';

if (!isLoggedIn() || getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();

$orderId = isset($_GET['order']) ? (int)$_GET['order'] : 0;

if (!$orderId) {
    die('Invalid order ID');
}

// Get order details
$sql = "SELECT o.*, p.product_name, p.category, p.unit,
               buyer.full_name as buyer_name, buyer.phone_number as buyer_phone, buyer.email as buyer_email,
               seller.full_name as seller_name, seller.phone_number as seller_phone,
               bp.business_name, bp.business_address, bp.tax_id,
               d.district_name as buyer_district
        FROM orders o
        INNER JOIN products p ON o.product_id = p.id
        INNER JOIN users buyer ON o.buyer_id = buyer.id
        INNER JOIN users seller ON o.seller_id = seller.id
        LEFT JOIN buyer_profiles bp ON buyer.id = bp.user_id
        LEFT JOIN districts d ON buyer.district_id = d.id
        WHERE o.id = ? AND o.buyer_id = ?";

$stmt = $db->prepare($sql);
$stmt->execute([$orderId, $currentUserId]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    die('Order not found');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice - <?php echo htmlspecialchars($order['order_number']); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @media print {
            .no-print { display: none; }
            body { margin: 0; }
        }
        .invoice-box {
            max-width: 800px;
            margin: auto;
            padding: 30px;
            border: 1px solid #eee;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.15);
            background: white;
        }
        .invoice-header {
            border-bottom: 3px solid #3b82f6;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }
        .invoice-table th {
            background: #f8f9fa;
        }
    </style>
</head>
<body>
    <div class="container my-5">
        <div class="invoice-box">
            <!-- Header -->
            <div class="invoice-header">
                <div class="row">
                    <div class="col-6">
                        <h2 class="text-primary mb-0">AIMS PLATFORM</h2>
                        <p class="mb-0">Agricultural Information Management System</p>
                    </div>
                    <div class="col-6 text-end">
                        <h4>INVOICE</h4>
                        <p class="mb-0"><strong><?php echo htmlspecialchars($order['order_number']); ?></strong></p>
                        <p class="mb-0"><?php echo date('F j, Y', strtotime($order['created_at'])); ?></p>
                    </div>
                </div>
            </div>
            
            <!-- Buyer & Seller Info -->
            <div class="row mb-4">
                <div class="col-6">
                    <h6 class="text-muted">BILL TO:</h6>
                    <strong><?php echo htmlspecialchars($order['business_name'] ?: $order['buyer_name']); ?></strong><br>
                    <?php if ($order['tax_id']): ?>
                    TIN: <?php echo htmlspecialchars($order['tax_id']); ?><br>
                    <?php endif; ?>
                    <?php echo htmlspecialchars($order['buyer_phone']); ?><br>
                    <?php if ($order['buyer_email']): ?>
                    <?php echo htmlspecialchars($order['buyer_email']); ?><br>
                    <?php endif; ?>
                    <?php if ($order['business_address']): ?>
                    <?php echo nl2br(htmlspecialchars($order['business_address'])); ?>
                    <?php endif; ?>
                </div>
                <div class="col-6">
                    <h6 class="text-muted">SOLD BY:</h6>
                    <strong><?php echo htmlspecialchars($order['seller_name']); ?></strong><br>
                    <?php echo htmlspecialchars($order['seller_phone']); ?><br>
                </div>
            </div>
            
            <!-- Items Table -->
            <table class="table invoice-table">
                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Quantity</th>
                        <th>Unit Price</th>
                        <th class="text-end">Total</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            <strong><?php echo htmlspecialchars($order['product_name']); ?></strong><br>
                            <small class="text-muted"><?php echo ucfirst(str_replace('_', ' ', $order['category'])); ?></small>
                        </td>
                        <td><?php echo number_format($order['quantity'], 2); ?> <?php echo htmlspecialchars($order['unit']); ?></td>
                        <td><?php echo formatCurrency($order['unit_price']); ?></td>
                        <td class="text-end"><?php echo formatCurrency($order['total_amount']); ?></td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="3" class="text-end"><strong>Subtotal:</strong></td>
                        <td class="text-end"><?php echo formatCurrency($order['total_amount']); ?></td>
                    </tr>
                    <tr>
                        <td colspan="3" class="text-end"><strong>Tax (0%):</strong></td>
                        <td class="text-end">UGX 0.00</td>
                    </tr>
                    <tr class="table-primary">
                        <td colspan="3" class="text-end"><strong>TOTAL:</strong></td>
                        <td class="text-end"><strong><?php echo formatCurrency($order['total_amount']); ?></strong></td>
                    </tr>
                </tfoot>
            </table>
            
            <!-- Order Details -->
            <div class="row mt-4">
                <div class="col-6">
                    <h6 class="text-muted">ORDER DETAILS:</h6>
                    <p class="mb-1"><strong>Status:</strong> <?php echo ucfirst($order['status']); ?></p>
                    <p class="mb-1"><strong>Payment Status:</strong> <?php echo ucfirst($order['payment_status']); ?></p>
                    <?php if ($order['payment_method']): ?>
                    <p class="mb-1"><strong>Payment Method:</strong> <?php echo ucfirst(str_replace('_', ' ', $order['payment_method'])); ?></p>
                    <?php endif; ?>
                </div>
                <div class="col-6">
                    <?php if ($order['delivery_address']): ?>
                    <h6 class="text-muted">DELIVERY ADDRESS:</h6>
                    <p><?php echo nl2br(htmlspecialchars($order['delivery_address'])); ?></p>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Footer -->
            <div class="mt-5 pt-3 border-top text-center text-muted">
                <p class="mb-0">Thank you for your business!</p>
                <p class="mb-0"><small>This is a system-generated invoice from AIMS Platform</small></p>
            </div>
            
            <!-- Actions -->
            <div class="no-print mt-4 text-center">
                <button onclick="window.print()" class="btn btn-primary me-2">
                    <i class="bi bi-printer"></i> Print Invoice
                </button>
                <a href="<?php echo APP_URL; ?>/buyer/order-details.php?id=<?php echo $order['id']; ?>" class="btn btn-secondary">
                    Back to Order
                </a>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>