<?php
include 'db.php';
// include 'auth.php'; // Temporarily removed - will be added later

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$quotation_id = intval($_GET['id'] ?? 0);
$store_id = $_SESSION['store_id'] ?? 1;

if (!$quotation_id) {
    die('Invalid quotation ID');
}

// Get quotation details
$quotation_stmt = $conn->prepare("
    SELECT q.*, u.username as created_by_name, s.store_name, s.address as store_address, s.phone as store_phone
    FROM quotations q
    LEFT JOIN users u ON q.created_by = u.id
    LEFT JOIN stores s ON q.store_id = s.id
    WHERE q.id = ? AND q.store_id = ?
");
$quotation_stmt->bind_param("ii", $quotation_id, $store_id);
$quotation_stmt->execute();
$quotation = $quotation_stmt->get_result()->fetch_assoc();

if (!$quotation) {
    die('Quotation not found');
}

// Get quotation items
$items_stmt = $conn->prepare("
    SELECT * FROM quotation_items 
    WHERE quotation_id = ? 
    ORDER BY id
");
$items_stmt->bind_param("i", $quotation_id);
$items_stmt->execute();
$items_result = $items_stmt->get_result();

$items = [];
while ($item = $items_result->fetch_assoc()) {
    $items[] = $item;
}

// Get branch information (same as sales receipt)
$branch_info = null;
$branch_result = $conn->query("SELECT * FROM branch_info LIMIT 1");
if ($branch_result && $branch_result->num_rows > 0) {
    $branch_info = $branch_result->fetch_assoc();
}

// Get store information (fallback to branch info if available)
$store_info = [
    'name' => $branch_info['branch_name'] ?? ($quotation['store_name'] ?? 'ITRPOS Store'),
    'address' => $branch_info['branch_address'] ?? ($quotation['store_address'] ?? 'Store Address'),
    'phone' => $branch_info['branch_phone'] ?? ($quotation['store_phone'] ?? 'Store Phone')
];
?>

<!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>
    <style>
        @media print {
            .no-print { display: none !important; }
            body { margin: 0; padding: 20px; }
        }
        
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            margin: 0;
            padding: 20px;
            background: #fff;
        }
        
        .header {
            text-align: center;
            border-bottom: 2px solid #007bff;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }
        
        .store-name {
            font-size: 24px;
            font-weight: bold;
            color: #007bff;
            margin: 0 0 10px 0;
        }
        
                 .store-info {
             font-size: 14px;
             color: #666;
             margin: 0;
             line-height: 1.4;
         }
        
        .quotation-title {
            font-size: 28px;
            font-weight: bold;
            color: #333;
            text-align: center;
            margin: 30px 0;
            text-transform: uppercase;
        }
        
        .quotation-details {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
        }
        
        .left-column, .right-column {
            flex: 1;
        }
        
        .detail-row {
            margin-bottom: 15px;
        }
        
        .detail-label {
            font-weight: bold;
            color: #666;
            font-size: 14px;
            margin-bottom: 5px;
        }
        
        .detail-value {
            font-size: 16px;
            color: #333;
        }
        
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 30px 0;
        }
        
        .items-table th {
            background: #f8f9fa;
            padding: 12px 8px;
            text-align: left;
            border-bottom: 2px solid #dee2e6;
            font-weight: bold;
            color: #495057;
        }
        
        .items-table td {
            padding: 12px 8px;
            border-bottom: 1px solid #dee2e6;
            vertical-align: top;
        }
        
        .items-table tr:nth-child(even) {
            background: #f8f9fa;
        }
        
        .item-name {
            font-weight: bold;
            color: #333;
        }
        
        .item-remarks {
            font-size: 12px;
            color: #666;
            font-style: italic;
            margin-top: 5px;
        }
        
        .totals-section {
            margin-top: 30px;
            text-align: right;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            font-size: 16px;
        }
        
        .total-label {
            font-weight: bold;
            color: #495057;
        }
        
        .total-value {
            color: #333;
            min-width: 120px;
            text-align: right;
        }
        
        .grand-total {
            font-size: 20px;
            font-weight: bold;
            color: #007bff;
            border-top: 2px solid #dee2e6;
            padding-top: 10px;
            margin-top: 10px;
        }
        
        .footer {
            margin-top: 50px;
            padding-top: 20px;
            border-top: 1px solid #dee2e6;
            text-align: center;
            color: #666;
            font-size: 14px;
        }
        
        .status-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .status-draft { background: #6c757d; color: white; }
        .status-sent { background: #007bff; color: white; }
        .status-accepted { background: #28a745; color: white; }
        .status-rejected { background: #dc3545; color: white; }
        .status-expired { background: #ffc107; color: black; }
        .status-converted { background: #17a2b8; color: white; }
        
        .print-button {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        
        .print-button:hover {
            background: #0056b3;
        }
        
        @media (max-width: 768px) {
            .quotation-details {
                flex-direction: column;
            }
            
            .left-column, .right-column {
                margin-bottom: 20px;
            }
            
            .items-table {
                font-size: 12px;
            }
            
            .items-table th, .items-table td {
                padding: 8px 4px;
            }
        }
    </style>
</head>
<body>
    <button class="print-button no-print" onclick="window.print()">
        🖨️ Print Quotation
    </button>

         <div class="header">
         <div class="store-name"><?php echo htmlspecialchars($store_info['name']); ?></div>
         <div class="store-info"><?php echo nl2br(htmlspecialchars($store_info['address'])); ?></div>
         <?php if (!empty($store_info['phone'])): ?>
             <div class="store-info">Phone: <?php echo htmlspecialchars($store_info['phone']); ?></div>
         <?php endif; ?>
         <?php if ($branch_info && !empty($branch_info['ntn'])): ?>
             <div class="store-info">NTN: <?php echo htmlspecialchars($branch_info['ntn']); ?></div>
         <?php endif; ?>
         <?php if ($branch_info && !empty($branch_info['strn'])): ?>
             <div class="store-info">STRN: <?php echo htmlspecialchars($branch_info['strn']); ?></div>
         <?php endif; ?>
     </div>

    <div class="quotation-title">Quotation</div>

    <div class="quotation-details">
        <div class="left-column">
            <div class="detail-row">
                <div class="detail-label">Quotation Number:</div>
                <div class="detail-value"><?php echo htmlspecialchars($quotation['quotation_number']); ?></div>
            </div>
            <div class="detail-row">
                <div class="detail-label">Customer:</div>
                <div class="detail-value"><?php echo htmlspecialchars($quotation['customer_name']); ?></div>
            </div>
            <div class="detail-row">
                <div class="detail-label">Quotation Date:</div>
                <div class="detail-value"><?php echo date('F d, Y', strtotime($quotation['quotation_date'])); ?></div>
            </div>
        </div>
        <div class="right-column">
            <div class="detail-row">
                <div class="detail-label">Status:</div>
                <div class="detail-value">
                    <span class="status-badge status-<?php echo $quotation['status']; ?>">
                        <?php echo ucfirst($quotation['status']); ?>
                    </span>
                </div>
            </div>
            <div class="detail-row">
                <div class="detail-label">Created By:</div>
                <div class="detail-value"><?php echo htmlspecialchars($quotation['created_by_name'] ?? 'Unknown'); ?></div>
            </div>
            <?php if (!empty($quotation['remarks'])): ?>
            <div class="detail-row">
                <div class="detail-label">Remarks:</div>
                <div class="detail-value"><?php echo htmlspecialchars($quotation['remarks']); ?></div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <table class="items-table">
        <thead>
            <tr>
                <th style="width: 40%;">Item Description</th>
                <th style="width: 10%; text-align: center;">Qty</th>
                <th style="width: 20%; text-align: right;">Unit Price</th>
                <th style="width: 15%; text-align: center;">Tax Rate</th>
                <th style="width: 15%; text-align: right;">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($items)): ?>
                <tr>
                    <td colspan="5" style="text-align: center; padding: 30px; color: #666;">
                        No items found
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($items as $item): ?>
                    <tr>
                        <td>
                            <div class="item-name"><?php echo htmlspecialchars($item['item_name']); ?></div>
                            <?php if (!empty($item['remarks'])): ?>
                                <div class="item-remarks"><?php echo htmlspecialchars($item['remarks']); ?></div>
                            <?php endif; ?>
                        </td>
                        <td style="text-align: center;"><?php echo $item['quantity']; ?></td>
                                                 <td style="text-align: right;"><?php echo number_format($item['unit_price'], 2); ?></td>
                        <td style="text-align: center;"><?php echo $item['tax_rate']; ?>%</td>
                                                 <td style="text-align: right;"><?php echo number_format($item['total_price'], 2); ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>

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

    <div class="footer">
        <p><strong>Thank you for your business!</strong></p>
        <p>Please contact us for any questions or modifications.</p>
        <p>Generated on: <?php echo date('F d, Y \a\t g:i A'); ?></p>
    </div>

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