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

requireLogin();

$invoiceId = $_GET['id'] ?? null;

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

try {
    $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([$invoiceId]);
    $invoice = $stmt->fetch();
    
    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 = ?
    ");
    $stmt->execute([$invoiceId]);
    $items = $stmt->fetchAll();
    
} 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>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>
        @media print {
            .no-print { display: none !important; }
            body { font-size: 12px; }
            .container { max-width: none !important; }
            
            /* Page break management */
            .page-break { page-break-before: always; }
            .no-page-break { page-break-inside: avoid; }
            .avoid-break { page-break-inside: avoid; }
            
            /* Keep header together */
            .invoice-header { page-break-inside: avoid; }
            
            /* Keep company and customer info together */
            .row.mb-4 { page-break-inside: avoid; }
            
            /* Table handling */
            .table-responsive { page-break-inside: auto; }
            .table { page-break-inside: auto; }
            .table thead { display: table-header-group; }
            .table tbody { display: table-row-group; }
            .table tr { page-break-inside: avoid; }
            
            /* Keep totals together */
            .row:last-child { page-break-inside: avoid; }
            
            /* Payment information and terms on new page if needed */
            .row.mt-4 { page-break-before: auto; }
            .mt-5 { page-break-before: auto; }
            
            /* Margin adjustments */
            @page { 
                margin: 1cm; 
                size: A4;
            }
        }
        .invoice-header {
            border-bottom: 3px solid #28a745;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }
        .company-info {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
        }
        .customer-info {
            background: #e8f5e8;
            padding: 20px;
            border-radius: 8px;
        }
        .invoice-details {
            background: #fff3cd;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .table th {
            background-color: #28a745;
            color: white;
            border: none;
        }
        .total-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
        }
        .payment-status {
            font-size: 1.2em;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <!-- Print Button -->
        <div class="no-print mb-3">
            <a href="invoices.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Invoices
            </a>
            <button onclick="window.print()" class="btn btn-primary">
                <i class="fas fa-print"></i> Print
            </button>
            <a href="download_invoice.php?id=<?php echo $invoiceId; ?>" class="btn btn-success">
                <i class="fas fa-download"></i> Download PDF
            </a>
        </div>
        
        <!-- Invoice Header -->
        <div class="invoice-header">
            <div class="row">
                <div class="col-md-6">
                    <h1 class="display-6 text-success">
                        <i class="fas fa-file-invoice-dollar"></i> INVOICE
                    </h1>
                    <h3 class="text-muted"><?php echo htmlspecialchars($invoice['invoice_number']); ?></h3>
                </div>
                <div class="col-md-6 text-end">
                    <div class="invoice-details">
                        <p class="mb-1"><strong>Issue Date:</strong> <?php echo date('d M Y', strtotime($invoice['issue_date'])); ?></p>
                        <p class="mb-1"><strong>Due Date:</strong> 
                            <?php 
                            $dueDate = strtotime($invoice['due_date']);
                            $today = time();
                            $isOverdue = $dueDate < $today && $invoice['payment_status'] != 'paid';
                            ?>
                            <span class="<?php echo $isOverdue ? 'text-danger fw-bold' : ''; ?>">
                                <?php echo date('d M Y', $dueDate); ?>
                            </span>
                            <?php if ($isOverdue): ?>
                                <br><small class="text-danger">OVERDUE</small>
                            <?php endif; ?>
                        </p>
                        <p class="mb-0"><strong>Payment Status:</strong> 
                            <span class="payment-status badge bg-<?php echo $invoice['payment_status'] == 'paid' ? 'success' : ($invoice['payment_status'] == 'partial' ? 'warning' : 'danger'); ?>">
                                <?php echo strtoupper($invoice['payment_status']); ?>
                            </span>
                        </p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Company and Customer Info -->
        <div class="row mb-4 no-page-break">
            <div class="col-md-6">
                <div class="company-info">
                    <h5 class="text-success mb-3">
                        <i class="fas fa-building"></i> From
                    </h5>
                    <img src="assets/img/logo.png" alt="The Sky Devlopers" width="150" height="150" class="img-fluid">
                                        
                    <p><strong>Company Name:</strong> The Sky Devlopers</p>
                    <p><strong>Address:</strong> FF-29 Shree Sidhheswar Harbours,waghodiya Road,NH-8 vadodara-390025, Vadodara, Gujarat 390011</p>
                    <p><strong>Contact:</strong> +91 70163 25717</p>
                    <p><strong>GST:</strong> NA</p>
                </div>
            </div>
            <div class="col-md-6">
                <div class="customer-info">
                    <h5 class="text-success mb-3">
                        <i class="fas fa-user"></i> Bill To
                    </h5>
                    <h4 class="mb-2"><?php echo htmlspecialchars($invoice['customer_name']); ?></h4>
                    <p class="mb-1"><i class="fas fa-phone"></i> <?php echo htmlspecialchars($invoice['contact_number']); ?></p>
                    <?php if ($invoice['email']): ?>
                    <p class="mb-1"><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($invoice['email']); ?></p>
                    <?php endif; ?>
                    <?php if ($invoice['address']): ?>
                    <p class="mb-1"><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($invoice['address']); ?></p>
                    <?php endif; ?>
                    <?php if ($invoice['gst_number']): ?>
                    <p class="mb-0"><i class="fas fa-id-card"></i> GST: <?php echo htmlspecialchars($invoice['gst_number']); ?></p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Items Table -->
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th width="5%">#</th>
                        <th width="35%">Description</th>
                        <th width="15%">Quantity</th>
                        <th width="15%">Rate (₹)</th>
                        <th width="15%">Amount (₹)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $index => $item): ?>
                    <tr>
                        <td><?php echo $index + 1; ?></td>
                        <td>
                            <strong><?php echo htmlspecialchars($item['material_name']); ?></strong>
                            <?php if ($item['description']): ?>
                            <br><small class="text-muted"><?php echo htmlspecialchars($item['description']); ?></small>
                            <?php endif; ?>
                        </td>
                        <td><?php echo $item['quantity']; ?></td>
                        <td>₹<?php echo number_format($item['rate'], 2); ?></td>
                        <td>₹<?php echo number_format($item['total'], 2); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Totals -->
        <div class="row avoid-break">
            <div class="col-md-8">
                <?php if ($invoice['notes']): ?>
                <div class="mt-4">
                    <h6 class="text-success">Notes:</h6>
                    <p class="text-muted"><?php echo nl2br(htmlspecialchars($invoice['notes'])); ?></p>
                </div>
                <?php endif; ?>
            </div>
            <div class="col-md-4">
                <div class="total-section">
                    <div class="d-flex justify-content-between mb-2">
                        <span>Subtotal:</span>
                        <span>₹<?php echo number_format($invoice['subtotal'], 2); ?></span>
                    </div>
                    <?php if ($invoice['tax_amount'] > 0): ?>
                    <div class="d-flex justify-content-between mb-2">
                        <span>Tax:</span>
                        <span>₹<?php echo number_format($invoice['tax_amount'], 2); ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if ($invoice['discount_amount'] > 0): ?>
                    <div class="d-flex justify-content-between mb-2">
                        <span>Discount:</span>
                        <span>-₹<?php echo number_format($invoice['discount_amount'], 2); ?></span>
                    </div>
                    <?php endif; ?>
                    <hr>
                    <div class="d-flex justify-content-between">
                        <strong>Total Amount:</strong>
                        <strong>₹<?php echo number_format($invoice['grand_total'], 2); ?></strong>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Payment Information -->
        <div class="row mt-4 page-break">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h6 class="mb-0"><i class="fas fa-credit-card"></i> Payment Information</h6>
                    </div>
                    <div class="card-body">
                        <p class="mb-1"><strong>Bank Name:</strong> NA</p>
                        <p class="mb-1"><strong>Account Number:</strong> NA</p>
                        <p class="mb-1"><strong>IFSC Code:</strong> NA</p>
                        <p class="mb-0"><strong>UPI ID:</strong> NA</p>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h6 class="mb-0"><i class="fas fa-info-circle"></i> Payment Terms</h6>
                    </div>
                    <div class="card-body">
                        <p class="mb-1">Payment due within 30 days of invoice date.</p>
                        <p class="mb-1">Late payments may incur additional charges.</p>
                        <p class="mb-0">Thank you for your business!</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Terms and Conditions -->
        <div class="mt-5 page-break">
            <h6 class="text-success">Terms & Conditions:</h6>
            <ul class="text-muted small">
                <li>Payment is due within 30 days of invoice date.</li>
                <li>Late payments may be subject to a 1.5% monthly service charge.</li>
                <li>All prices are exclusive of applicable taxes unless otherwise stated.</li>
                <li>Goods once sold will not be taken back.</li>
            </ul>
        </div>
        
        <!-- Signature -->
        <div class="row mt-5 avoid-break">
            <div class="col-md-6">
                <p class="text-muted">Customer Signature</p>
                <div style="border-bottom: 1px solid #ccc; width: 200px; height: 50px;"></div>
            </div>
            <div class="col-md-6 text-end">
                <p class="text-muted">Authorized Signature</p>
                <div style="border-bottom: 1px solid #ccc; width: 200px; height: 50px; margin-left: auto;"></div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
