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

requireLogin();

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

if (!$quotationId) {
    header('Location: quotations.php');
    exit();
}

try {
    $pdo = getConnection();
    
    // Get quotation details
    $stmt = $pdo->prepare("
        SELECT q.*, c.name as customer_name, c.contact_number, c.email, c.address, c.gst_number
        FROM quotations q 
        JOIN customers c ON q.customer_id = c.id 
        WHERE q.id = ?
    ");
    $stmt->execute([$quotationId]);
    $quotation = $stmt->fetch();
    
    if (!$quotation) {
        header('Location: quotations.php');
        exit();
    }
    
    // Get quotation items
    $stmt = $pdo->prepare("
        SELECT qi.*, m.name as material_name, m.description
        FROM quotation_items qi
        JOIN materials m ON qi.material_id = m.id
        WHERE qi.quotation_id = ?
    ");
    $stmt->execute([$quotationId]);
    $items = $stmt->fetchAll();
    
} catch (Exception $e) {
    header('Location: quotations.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quotation <?php echo htmlspecialchars($quotation['quotation_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 */
            .quotation-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; }
            
            /* Terms and signature on new page if needed */
            .mt-5 { page-break-before: auto; }
            
            /* Margin adjustments */
            @page { 
                margin: 1cm; 
                size: A4;
            }
        }
        .quotation-header {
            border-bottom: 3px solid #007bff;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }
        .company-info {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
        }
        .customer-info {
            background: #e3f2fd;
            padding: 20px;
            border-radius: 8px;
        }
        .quotation-details {
            background: #fff3cd;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .table th {
            background-color: #007bff;
            color: white;
            border: none;
        }
        .total-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
        }

        .display-6{
            font-size: calc(0.375rem + 1.5vw);
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <!-- Print Button -->
        <div class="no-print mb-3">
            <a href="quotations.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Quotations
            </a>
            <button onclick="window.print()" class="btn btn-primary">
                <i class="fas fa-print"></i> Print
            </button>
            <a href="download_quotation.php?id=<?php echo $quotationId; ?>" class="btn btn-success">
                <i class="fas fa-download"></i> Download PDF
            </a>
        </div>
        
        <!-- Quotation Header -->
        <div class="quotation-header">
            <div class="row">
                <div class="col-md-8">
                    <h1 class="display-6 text-primary">
                        <i class="fas fa-file-invoice"></i> QUOTATION: <?php echo htmlspecialchars($quotation['quotation_number']); ?>
                    </h1>
                    <h3 class="text-muted"></h3>
                </div>
                <div class="col-md-4 text-end">
                    <div class="quotation-details">
                        <p class="mb-1"><strong>Date:</strong> <?php echo date('d M Y', strtotime($quotation['issue_date'])); ?></p>
                        <!-- <p class="mb-1"><strong>Status:</strong> 
                            <span class="badge bg-<?php echo $quotation['status'] == 'accepted' ? 'success' : ($quotation['status'] == 'rejected' ? 'danger' : 'warning'); ?>">
                                <?php echo ucfirst($quotation['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-primary mb-3">
                        <i class="fas fa-building"></i> From
                    </h5>
                    <img src="assets/img/logo.png" alt="The Sky Devlopers" width="100" height="100" class="img-fluid">
                    <h4>The Sky Developers</h4>
                    <!-- <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-primary mb-3">
                        <i class="fas fa-user"></i> To
                    </h5>
                    <h4 class="mb-2"><?php echo htmlspecialchars($quotation['customer_name']); ?></h4>
                    <p class="mb-1"><i class="fas fa-phone"></i> <?php echo htmlspecialchars($quotation['contact_number']); ?></p>
                    <?php if ($quotation['email']): ?>
                    <p class="mb-1"><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($quotation['email']); ?></p>
                    <?php endif; ?>
                    <?php if ($quotation['address']): ?>
                    <p class="mb-1"><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($quotation['address']); ?></p>
                    <?php endif; ?>
                    <?php if ($quotation['gst_number']): ?>
                    <p class="mb-0"><i class="fas fa-id-card"></i> GST: <?php echo htmlspecialchars($quotation['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 ($quotation['notes']): ?>
                <div class="mt-4">
                    <h6 class="text-primary">Notes:</h6>
                    <p class="text-muted"><?php echo nl2br(htmlspecialchars($quotation['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($quotation['subtotal'], 2); ?></span>
                    </div>
                    <?php if ($quotation['tax_amount'] > 0): ?>
                    <div class="d-flex justify-content-between mb-2">
                        <span>Tax:</span>
                        <span>₹<?php echo number_format($quotation['tax_amount'], 2); ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if ($quotation['discount_amount'] > 0): ?>
                    <div class="d-flex justify-content-between mb-2">
                        <span>Discount:</span>
                        <span>-₹<?php echo number_format($quotation['discount_amount'], 2); ?></span>
                    </div>
                    <?php endif; ?>
                    <hr>
                    <div class="d-flex justify-content-between">
                        <strong>Total Amount:</strong>
                        <strong>₹<?php echo number_format($quotation['grand_total'], 2); ?></strong>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Terms and Conditions -->
        <div class="mt-5 page-break">
            <h6 class="text-primary">Terms & Conditions:</h6>
            <ul class="text-muted small">
                <li>This quotation is valid for 30 days from the date of issue.</li>
                <li>Payment terms: 50% advance, 50% on delivery.</li>
                <li>Delivery time: 7-10 working days after order confirmation.</li>
                <li>All prices are exclusive of applicable taxes.</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>
