<?php
session_start();
include '../db.php';

// Temporarily removed authentication check - will be added later
// if (!isset($_SESSION['user_id'])) {
//     echo json_encode(['success' => false, 'message' => 'User not authenticated']);
//     exit;
// }

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

if (!$quotation_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid quotation ID']);
    exit;
}

try {
    // Get quotation header
    $quotation_stmt = $conn->prepare("
        SELECT q.*, u.username as created_by_name
        FROM quotations q
        LEFT JOIN users u ON q.created_by = u.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) {
        echo json_encode(['success' => false, 'message' => 'Quotation not found']);
        exit;
    }
    
    // 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;
    }
    
    // Generate HTML for the modal
    $html = generateQuotationHTML($quotation, $items);
    
    echo json_encode([
        'success' => true,
        'html' => $html,
        'quotation' => $quotation,
        'items' => $items
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching quotation details: ' . $e->getMessage()
    ]);
}

function generateQuotationHTML($quotation, $items) {
    $status_badge_class = getStatusBadgeClass($quotation['status']);
    $status_label = ucfirst($quotation['status']);
    
    $html = '
    <div class="quotation-details">
        <div class="row mb-3">
            <div class="col-md-6">
                <h6 class="text-muted mb-1">Quotation Number</h6>
                <h5 class="mb-0">' . htmlspecialchars($quotation['quotation_number']) . '</h5>
            </div>
            <div class="col-md-6 text-end">
                <h6 class="text-muted mb-1">Status</h6>
                <span class="badge ' . $status_badge_class . ' fs-6">' . $status_label . '</span>
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col-md-6">
                <h6 class="text-muted mb-1">Customer</h6>
                <p class="mb-0">' . htmlspecialchars($quotation['customer_name']) . '</p>
            </div>
            <div class="col-md-6">
                <h6 class="text-muted mb-1">Quotation Date</h6>
                <p class="mb-0">' . date('M d, Y', strtotime($quotation['quotation_date'])) . '</p>
            </div>
        </div>
        
        <div class="row mb-3">
            <div class="col-md-6">
                <h6 class="text-muted mb-1">Created By</h6>
                <p class="mb-0">' . htmlspecialchars($quotation['created_by_name'] ?? 'Unknown') . '</p>
            </div>
        </div>';
    
    if (!empty($quotation['remarks'])) {
        $html .= '
        <div class="row mb-3">
            <div class="col-12">
                <h6 class="text-muted mb-1">Remarks</h6>
                <p class="mb-0">' . htmlspecialchars($quotation['remarks']) . '</p>
            </div>
        </div>';
    }
    
    $html .= '
        <hr>
        <h6 class="mb-3">Items</h6>
        <div class="table-responsive">
            <table class="table table-sm">
                <thead class="table-light">
                    <tr>
                        <th>Item</th>
                        <th class="text-center">Qty</th>
                        <th class="text-end">Unit Price</th>
                        <th class="text-end">Total</th>
                        <th class="text-center">Tax</th>
                    </tr>
                </thead>
                <tbody>';
    
    if (empty($items)) {
        $html .= '
                    <tr>
                        <td colspan="5" class="text-center text-muted py-3">
                            No items found
                        </td>
                    </tr>';
    } else {
        foreach ($items as $item) {
            $html .= '
                    <tr>
                        <td>
                            <div>
                                <strong>' . htmlspecialchars($item['item_name']) . '</strong>';
            
            if (!empty($item['remarks'])) {
                $html .= '<br><small class="text-muted">' . htmlspecialchars($item['remarks']) . '</small>';
            }
            
            $html .= '
                            </div>
                        </td>
                        <td class="text-center">' . $item['quantity'] . '</td>
                        <td class="text-end">' . number_format($item['unit_price'], 2) . '</td>
                        <td class="text-end">' . number_format($item['total_price'], 2) . '</td>
                        <td class="text-center">' . $item['tax_rate'] . '%</td>
                    </tr>';
        }
    }
    
    $html .= '
                </tbody>
            </table>
        </div>
        
        <hr>
        <div class="row">
            <div class="col-md-6 offset-md-6">
                <table class="table table-sm table-borderless">
                    <tr>
                        <td>Subtotal:</td>
                        <td class="text-end">' . number_format($quotation['subtotal'], 2) . '</td>
                    </tr>
                    <tr>
                        <td>Tax Amount:</td>
                        <td class="text-end">' . number_format($quotation['tax_amount'], 2) . '</td>
                    </tr>';
    
    if ($quotation['discount_amount'] > 0) {
        $html .= '
                    <tr>
                        <td>Discount:</td>
                        <td class="text-end">-' . number_format($quotation['discount_amount'], 2) . '</td>
                    </tr>';
    }
    
    $html .= '
                    <tr class="fw-bold">
                        <td>Total:</td>
                        <td class="text-end">' . number_format($quotation['net_amount'], 2) . '</td>
                    </tr>
                </table>
            </div>
        </div>';
    
    if ($quotation['status'] === 'draft') {
        $html .= '
        <div class="alert alert-info mt-3">
            <i class="fas fa-info-circle"></i>
            <strong>Note:</strong> This is a draft quotation. You can edit it or convert it to a sale when ready.
        </div>';
    } elseif ($quotation['status'] === 'converted') {
        $html .= '
        <div class="alert alert-success mt-3">
            <i class="fas fa-check-circle"></i>
            <strong>Converted:</strong> This quotation has been converted to a sale.
        </div>';
    }
    
    $html .= '
    </div>';
    
    return $html;
}

function getStatusBadgeClass($status) {
    switch ($status) {
        case 'draft': return 'bg-secondary';
        case 'sent': return 'bg-primary';
        case 'accepted': return 'bg-success';
        case 'rejected': return 'bg-danger';
        case 'expired': return 'bg-warning';
        case 'converted': return 'bg-info';
        default: return 'bg-secondary';
    }
}
?>
