<?php
require_once 'config/database.php';
require_once 'config/session.php';
require_once 'includes/header.php';

requireLogin();

// Get invoice ID
$invoice_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$invoice_id) {
    header('Location: invoices.php');
    exit;
}

try {
    // Get database connection
    $pdo = getConnection();
    
    // Get invoice details
    $stmt = $pdo->prepare("
        SELECT i.*, c.name as customer_name, c.contact_number, c.email, c.address, c.gst_number
        FROM invoices i
        JOIN customers c ON i.customer_id = c.id
        WHERE i.id = ?
    ");
    $stmt->execute([$invoice_id]);
    $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$invoice) {
        header('Location: invoices.php');
        exit;
    }
    
    // Get invoice items
    $stmt = $pdo->prepare("
        SELECT ii.*, m.name as material_name, m.description
        FROM invoice_items ii
        JOIN materials m ON ii.material_id = m.id
        WHERE ii.invoice_id = ?
        ORDER BY ii.id
    ");
    $stmt->execute([$invoice_id]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    header('Location: invoices.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Download Invoice - <?php echo htmlspecialchars($invoice['invoice_number']); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .download-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            text-align: center;
        }
        .download-section h4 {
            margin-bottom: 20px;
        }
        .download-section .btn {
            margin: 5px;
            min-width: 150px;
        }
        .invoice-preview {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .invoice-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .invoice-body {
            padding: 30px;
        }
        .company-info, .customer-info {
            margin-bottom: 30px;
        }
        .items-table {
            margin: 20px 0;
        }
        .total-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-top: 20px;
        }
        .status {
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: bold;
            font-size: 12px;
        }
        .status-paid {
            background-color: #d4edda;
            color: #155724;
        }
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        .status-partial {
            background-color: #f8d7da;
            color: #721c24;
        }
        .no-print {
            display: block;
        }
        @media print {
            .no-print {
                display: none !important;
            }
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <!-- Download Section -->
        <div class="download-section no-print">
            <h4><i class="fas fa-file-pdf"></i> Download Invoice as PDF</h4>
            <p>Click the button below to download this invoice as a PDF file.</p>
            <a href="pdf_invoice.php?id=<?php echo $invoice['id']; ?>" class="btn btn-light btn-lg" target="_blank">
                <i class="fas fa-download"></i> Download PDF
            </a>
            <a href="invoices.php" class="btn btn-outline-light">
                <i class="fas fa-arrow-left"></i> Back to Invoices
            </a>
        </div>
        
        <!-- Invoice Preview -->
        <div class="invoice-preview">
            <div class="invoice-header">
                <h1><i class="fas fa-file-invoice-dollar"></i> INVOICE</h1>
                <h2><?php echo htmlspecialchars($invoice['invoice_number']); ?></h2>
                <p class="mb-0">
                    Issue Date: <?php echo date('d M Y', strtotime($invoice['issue_date'])); ?> | 
                    Due Date: <?php echo date('d M Y', strtotime($invoice['due_date'])); ?>
                </p>
                <p class="mb-0 mt-2">
                    Status: <span class="status status-<?php echo strtolower($invoice['payment_status']); ?>">
                        <?php echo ucfirst($invoice['payment_status']); ?>
                    </span>
                </p>
            </div>
            
            <div class="invoice-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="company-info">
                            <h4><i class="fas fa-building"></i> From: THE SKY Developers</h4>
                            <p class="mb-1">FF-29 Shree Sidhheswar Harbours,</p>
                            <p class="mb-1">Waghodiya Road, NH-8</p>
                            <p class="mb-1">Vadodara - 390025</p>
                            <p class="mb-1">Phone: +91 70163 25717</p>
                            <p class="mb-1">Email: theskydevelopers@yahoo.com</p>
                            <p class="mb-0">GST: NA</p>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="customer-info">
                            <h4><i class="fas fa-user"></i> Bill To:</h4>
                            <p class="mb-1"><strong><?php echo htmlspecialchars($invoice['customer_name']); ?></strong></p>
                            <p class="mb-1">Phone: <?php echo htmlspecialchars($invoice['contact_number']); ?></p>
                            <p class="mb-1">Email: <?php echo htmlspecialchars($invoice['email']); ?></p>
                            <p class="mb-1">Address: <?php echo htmlspecialchars($invoice['address']); ?></p>
                            <p class="mb-0">GST: <?php echo htmlspecialchars($invoice['gst_number']); ?></p>
                        </div>
                    </div>
                </div>
                
                <div class="items-table">
                    <table class="table table-bordered">
                        <thead class="table-dark">
                            <tr>
                                <th>#</th>
                                <th>Material</th>
                                <th>Description</th>
                                <th class="text-end">Quantity</th>
                                <th class="text-end">Rate</th>
                                <th class="text-end">Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($items as $index => $item): ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td><?php echo htmlspecialchars($item['material_name']); ?></td>
                                <td><?php echo htmlspecialchars($item['description']); ?></td>
                                <td class="text-end"><?php echo $item['quantity']; ?></td>
                                <td class="text-end">₹<?php echo number_format($item['rate'], 2); ?></td>
                                <td class="text-end">₹<?php echo number_format($item['total'], 2); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <div class="total-section">
                    <div class="row">
                        <div class="col-md-8"></div>
                        <div class="col-md-4">
                            <div class="d-flex justify-content-between">
                                <strong>Subtotal:</strong>
                                <strong>₹<?php echo number_format($invoice['subtotal'], 2); ?></strong>
                            </div>
                            <div class="d-flex justify-content-between">
                                <strong>Grand Total:</strong>
                                <strong>₹<?php echo number_format($invoice['grand_total'], 2); ?></strong>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php if (!empty($invoice['notes'])): ?>
                <div class="mt-4">
                    <h5>Notes:</h5>
                    <p><?php echo nl2br(htmlspecialchars($invoice['notes'])); ?></p>
                </div>
                <?php endif; ?>
                
                <div class="text-center mt-4">
                    <p class="text-muted">Thank you for your business!</p>
                    <p class="text-muted"><small>Payment due within <?php echo date('d M Y', strtotime($invoice['due_date'])); ?></small></p>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>