<?php
session_start();
require_once 'layouts/dbconn.php';

// Essential utility functions defined inline
function formatDateTime($datetime, $format = 'M j, Y g:i A') {
    if (empty($datetime) || $datetime === '0000-00-00 00:00:00') {
        return 'Not set';
    }
    
    try {
        $date = new DateTime($datetime);
        return $date->format($format);
    } catch (Exception $e) {
        return 'Invalid date';
    }
}

function formatDate($date, $format = 'M j, Y') {
    if (empty($date) || $date === '0000-00-00') {
        return 'Not set';
    }
    
    try {
        $dateObj = new DateTime($date);
        return $dateObj->format($format);
    } catch (Exception $e) {
        return 'Invalid date';
    }
}

function calculateAge($dob) {
    if (empty($dob) || $dob === '0000-00-00') {
        return 0;
    }
    
    try {
        $birthDate = new DateTime($dob);
        $today = new DateTime('today');
        return $birthDate->diff($today)->y;
    } catch (Exception $e) {
        return 0;
    }
}

function hasPermission($permission) {
    global $conn;
    
    if (!isset($_SESSION['user_id'])) {
        return false;
    }
    
    // Super Admin has all permissions
    if (isset($_SESSION['role_name']) && $_SESSION['role_name'] === 'Super Admin') {
        return true;
    }
    
    // Check specific permission
    try {
        $sql = "SELECT COUNT(*) as has_permission 
                FROM users u 
                JOIN role_permissions rp ON u.role_id = rp.role_id 
                JOIN permissions p ON rp.permission_id = p.permission_id 
                WHERE u.user_id = ? AND p.name = ? AND u.status = 'ACTIVE'";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("is", $_SESSION['user_id'], $permission);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        return $result['has_permission'] > 0;
    } catch (Exception $e) {
        error_log("Permission check error: " . $e->getMessage());
        return false;
    }
}

/*function includeFileWithVariables($filePath, $variables = []) {
    extract($variables);
    include $filePath;
}*/

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_name'] ?? '';

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

if (!$quote_id) {
    header('Location: list_quotes.php?error=invalid_quote');
    exit();
}

// Fetch quote details with related information
$sql = "SELECT 
    q.*,
    COALESCE(c.first_name, l.first_name, JSON_UNQUOTE(JSON_EXTRACT(q.insured_details, '$.primary_insured.name'))) as customer_first_name,
    COALESCE(c.last_name, l.last_name, '') as customer_last_name,
    COALESCE(c.customer_number, l.lead_number, '') as customer_reference,
    COALESCE(c.phone_primary, l.phone, '') as customer_phone,
    COALESCE(c.email, l.email, '') as customer_email,
    COALESCE(c.date_of_birth, '') as customer_dob,
    COALESCE(c.gender, '') as customer_gender,
    COALESCE(c.national_id, '') as customer_national_id,
    COALESCE(c.address_line1, '') as customer_address,
    ip.product_name,
    ip.product_code,
    ip.description as product_description,
    ip.key_features,
    ip.benefits,
    ip.exclusions,
    pc.category_name,
    ic.company_name,
    ic.company_code,
    u.full_name as agent_name,
    u.agent_code,
    u.phone_number as agent_phone,
    u.email as agent_email,
    CASE 
        WHEN q.expires_at < NOW() AND q.status = 'ACTIVE' THEN 'EXPIRED'
        ELSE q.status 
    END as effective_status,
    DATEDIFF(q.expires_at, NOW()) as days_to_expire,
    p.policy_number as converted_policy_number
FROM quotes q
LEFT JOIN customers c ON q.customer_id = c.customer_id
LEFT JOIN leads l ON q.lead_id = l.lead_id
LEFT JOIN insurance_products ip ON q.product_id = ip.product_id
LEFT JOIN product_categories pc ON ip.category_id = pc.category_id
LEFT JOIN insurance_companies ic ON ip.company_id = ic.company_id
LEFT JOIN users u ON q.agent_id = u.user_id
LEFT JOIN policies p ON q.converted_policy_id = p.policy_id
WHERE q.quote_id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $quote_id);
$stmt->execute();
$quote = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$quote) {
    header('Location: list_quotes.php?error=quote_not_found');
    exit();
}

// Check access permissions (agents can only view their own quotes unless they have broader permissions)
if ($user_role === 'Insurance Agent' && !hasPermission('quotes_view_all') && $quote['agent_id'] != $user_id) {
    header('Location: list_quotes.php?error=access_denied');
    exit();
}

// Parse JSON fields
$insured_details = json_decode($quote['insured_details'], true) ?? [];
$risk_factors = json_decode($quote['risk_factors'], true) ?? [];
$product_features = json_decode($quote['key_features'], true) ?? [];
$product_benefits = json_decode($quote['benefits'], true) ?? [];
$product_exclusions = json_decode($quote['exclusions'], true) ?? [];

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Quote - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .quote-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .info-card {
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            border-radius: 15px;
            margin-bottom: 1.5rem;
        }
        
        .info-card .card-header {
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
            border-radius: 15px 15px 0 0;
            padding: 1rem 1.5rem;
        }
        
        .status-badge {
            font-size: 0.875rem;
            padding: 0.5rem 1rem;
            border-radius: 25px;
            font-weight: 600;
        }
        
        .premium-breakdown {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
        }
        
        .premium-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.75rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid rgba(255,255,255,0.2);
        }
        
        .premium-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            font-size: 1.25rem;
            font-weight: 700;
        }
        
        .action-buttons {
            position: sticky;
            top: 20px;
            z-index: 10;
        }
        
        .feature-list {
            list-style: none;
            padding: 0;
        }
        
        .feature-list li {
            padding: 0.5rem 0;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
        }
        
        .feature-list li:last-child {
            border-bottom: none;
        }
        
        .feature-list li::before {
            content: "✓";
            color: #28a745;
            font-weight: bold;
            margin-right: 0.75rem;
            font-size: 1.1rem;
        }
        
        .exclusion-list li::before {
            content: "⨯";
            color: #dc3545;
        }
        
        .expiry-warning {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            color: white;
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 1rem;
        }
        
        .timeline-item {
            padding: 1rem;
            border-left: 3px solid #007bff;
            margin-bottom: 1rem;
            background: #f8f9ff;
            border-radius: 0 10px 10px 0;
        }
        
        .dependent-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            border-left: 4px solid #007bff;
        }
        
        .risk-indicator {
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.875rem;
            font-weight: 600;
        }
        
        .risk-low { background: #d4edda; color: #155724; }
        .risk-medium { background: #fff3cd; color: #856404; }
        .risk-high { background: #f8d7da; color: #721c24; }
        
        @media print {
            .action-buttons, .no-print { display: none !important; }
            .quote-header { background: #333 !important; }
            .premium-breakdown { background: #555 !important; }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Quote Details</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_quotes.php">Quotes</a></li>
                                        <li class="breadcrumb-item active">View Quote</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quote Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="quote-header">
                                <div class="row align-items-center">
                                    <div class="col-md-6">
                                        <h2 class="mb-2"><?php echo htmlspecialchars($quote['quote_number']); ?></h2>
                                        <p class="mb-0 opacity-75">
                                            Generated on <?php echo formatDateTime($quote['created_at'], 'M j, Y g:i A'); ?>
                                        </p>
                                        <p class="mb-0 opacity-75">
                                            Agent: <?php echo htmlspecialchars($quote['agent_name'] . ' (' . $quote['agent_code'] . ')'); ?>
                                        </p>
                                    </div>
                                    <div class="col-md-6 text-md-end">
                                        <?php 
                                        $status_class = match($quote['effective_status']) {
                                            'ACTIVE' => 'bg-success',
                                            'CONVERTED' => 'bg-info',
                                            'EXPIRED' => 'bg-danger',
                                            'REJECTED' => 'bg-secondary',
                                            'PENDING' => 'bg-warning',
                                            'DRAFT' => 'bg-light text-dark',
                                            default => 'bg-secondary'
                                        };
                                        ?>
                                        <span class="status-badge <?php echo $status_class; ?>">
                                            <?php echo ucfirst(strtolower($quote['effective_status'])); ?>
                                        </span>
                                        
                                        <?php if($quote['converted_policy_number']): ?>
                                        <div class="mt-2">
                                            <small>Converted to Policy: 
                                                <a href="policies/view_policy.php?number=<?php echo $quote['converted_policy_number']; ?>" 
                                                   class="text-white text-decoration-underline">
                                                    <?php echo htmlspecialchars($quote['converted_policy_number']); ?>
                                                </a>
                                            </small>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Expiry Warning -->
                    <?php if($quote['effective_status'] === 'ACTIVE' && $quote['days_to_expire'] <= 7): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="expiry-warning">
                                <div class="d-flex align-items-center">
                                    <i class="ri-time-line fs-4 me-3"></i>
                                    <div>
                                        <h6 class="mb-1">Quote Expiring Soon</h6>
                                        <p class="mb-0">
                                            This quote will expire in <?php echo $quote['days_to_expire']; ?> day(s) 
                                            on <?php echo formatDateTime($quote['expires_at'], 'M j, Y g:i A'); ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Main Content -->
                        <div class="col-xl-8">
                            <!-- Customer Information -->
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-user-line me-2"></i>
                                        Customer Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="d-flex align-items-center mb-3">
                                                <div class="avatar-lg me-3">
                                                    <span class="avatar-title bg-soft-primary text-primary rounded-circle fs-3">
                                                        <?php echo strtoupper(substr($quote['customer_first_name'], 0, 1)); ?>
                                                    </span>
                                                </div>
                                                <div>
                                                    <h5 class="mb-1">
                                                        <?php echo htmlspecialchars($quote['customer_first_name'] . ' ' . $quote['customer_last_name']); ?>
                                                    </h5>
                                                    <?php if($quote['customer_reference']): ?>
                                                    <p class="text-muted mb-0"><?php echo htmlspecialchars($quote['customer_reference']); ?></p>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="table-responsive">
                                                <table class="table table-borderless table-sm">
                                                    <?php if($quote['customer_phone']): ?>
                                                    <tr>
                                                        <td class="text-muted">Phone:</td>
                                                        <td>
                                                            <a href="tel:<?php echo $quote['customer_phone']; ?>">
                                                                <?php echo htmlspecialchars($quote['customer_phone']); ?>
                                                            </a>
                                                        </td>
                                                    </tr>
                                                    <?php endif; ?>
                                                    
                                                    <?php if($quote['customer_email']): ?>
                                                    <tr>
                                                        <td class="text-muted">Email:</td>
                                                        <td>
                                                            <a href="mailto:<?php echo $quote['customer_email']; ?>">
                                                                <?php echo htmlspecialchars($quote['customer_email']); ?>
                                                            </a>
                                                        </td>
                                                    </tr>
                                                    <?php endif; ?>
                                                    
                                                    <?php if($quote['customer_dob']): ?>
                                                    <tr>
                                                        <td class="text-muted">Date of Birth:</td>
                                                        <td>
                                                            <?php echo formatDate($quote['customer_dob']); ?>
                                                            (<?php echo calculateAge($quote['customer_dob']); ?> years)
                                                        </td>
                                                    </tr>
                                                    <?php endif; ?>
                                                    
                                                    <?php if($quote['customer_gender']): ?>
                                                    <tr>
                                                        <td class="text-muted">Gender:</td>
                                                        <td><?php echo ucwords(strtolower($quote['customer_gender'])); ?></td>
                                                    </tr>
                                                    <?php endif; ?>
                                                    
                                                    <?php if($quote['customer_national_id']): ?>
                                                    <tr>
                                                        <td class="text-muted">National ID:</td>
                                                        <td><?php echo htmlspecialchars($quote['customer_national_id']); ?></td>
                                                    </tr>
                                                    <?php endif; ?>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Premium Breakdown -->
                            <div class="premium-breakdown">
                                <h5 class="mb-3">
                                    <i class="ri-money-dollar-circle-line me-2"></i>
                                    Premium Breakdown
                                </h5>
                                
                                <div class="premium-item">
                                    <span>Coverage Amount:</span>
                                    <span>KSH <?php echo number_format($quote['coverage_amount'], 2); ?></span>
                                </div>
                                
                                <div class="premium-item">
                                    <span>Base Premium:</span>
                                    <span>KSH <?php echo number_format($quote['base_premium'], 2); ?></span>
                                </div>
                                
                                <?php if($quote['risk_premium'] > 0): ?>
                                <div class="premium-item">
                                    <span>Risk Premium:</span>
                                    <span>KSH <?php echo number_format($quote['risk_premium'], 2); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if($quote['loading_amount'] > 0): ?>
                                <div class="premium-item">
                                    <span>Loading:</span>
                                    <span>KSH <?php echo number_format($quote['loading_amount'], 2); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if($quote['discount_amount'] > 0): ?>
                                <div class="premium-item">
                                    <span>Discount:</span>
                                    <span class="text-warning">- KSH <?php echo number_format($quote['discount_amount'], 2); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <div class="premium-item">
                                    <span>Subtotal:</span>
                                    <span>KSH <?php echo number_format($quote['total_premium'], 2); ?></span>
                                </div>
                                
                                <div class="premium-item">
                                    <span>Policy Fee:</span>
                                    <span>KSH <?php echo number_format($quote['policy_fee'], 2); ?></span>
                                </div>
                                
                                <div class="premium-item">
                                    <span>Stamp Duty:</span>
                                    <span>KSH <?php echo number_format($quote['stamp_duty'], 2); ?></span>
                                </div>
                                
                                <div class="premium-item">
                                    <span>VAT (16%):</span>
                                    <span>KSH <?php echo number_format($quote['tax_amount'], 2); ?></span>
                                </div>
                                
                                <div class="premium-item">
                                    <span><strong>TOTAL PREMIUM:</strong></span>
                                    <span><strong>KSH <?php echo number_format($quote['final_premium'], 2); ?></strong></span>
                                </div>
                                
                                <div class="mt-3 text-center">
                                    <small class="opacity-75">
                                        <?php echo ucwords(str_replace('_', ' ', strtolower($quote['premium_frequency']))); ?> Premium
                                    </small>
                                </div>
                                
                                <?php if($quote['commission_amount'] > 0): ?>
                                <div class="mt-3 pt-2" style="border-top: 1px solid rgba(255,255,255,0.2);">
                                    <div class="d-flex justify-content-between">
                                        <small>Agent Commission:</small>
                                        <small>KSH <?php echo number_format($quote['commission_amount'], 2); ?></small>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Product Information -->
                            <div class="card info-card mt-4">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-shield-check-line me-2"></i>
                                        Product Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row mb-3">
                                        <div class="col-md-8">
                                            <h5 class="text-primary mb-2"><?php echo htmlspecialchars($quote['product_name']); ?></h5>
                                            <p class="text-muted mb-1">
                                                <strong>Company:</strong> <?php echo htmlspecialchars($quote['company_name']); ?>
                                            </p>
                                            <p class="text-muted mb-1">
                                                <strong>Category:</strong> <?php echo htmlspecialchars($quote['category_name']); ?>
                                            </p>
                                            <p class="text-muted mb-0">
                                                <strong>Product Code:</strong> <?php echo htmlspecialchars($quote['product_code']); ?>
                                            </p>
                                        </div>
                                        <div class="col-md-4 text-md-end">
                                            <div class="row text-center">
                                                <div class="col-12 mb-2">
                                                    <span class="badge bg-soft-info text-info px-3 py-2">
                                                        <?php echo ucwords(str_replace('_', ' ', $quote['quote_type'])); ?>
                                                    </span>
                                                </div>
                                                <div class="col-12">
                                                    <span class="badge bg-soft-secondary text-secondary px-3 py-2">
                                                        <?php echo ucwords(str_replace('_', ' ', strtolower($quote['premium_frequency']))); ?>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <?php if($quote['product_description']): ?>
                                    <div class="mb-3">
                                        <h6 class="text-muted mb-2">Description</h6>
                                        <p class="mb-0"><?php echo nl2br(htmlspecialchars($quote['product_description'])); ?></p>
                                    </div>
                                    <?php endif; ?>

                                    <div class="row">
                                        <?php if(!empty($product_features)): ?>
                                        <div class="col-md-4">
                                            <h6 class="text-success mb-3">Key Features</h6>
                                            <ul class="feature-list">
                                                <?php foreach($product_features as $feature): ?>
                                                <li><?php echo htmlspecialchars($feature); ?></li>
                                                <?php endforeach; ?>
                                            </ul>
                                        </div>
                                        <?php endif; ?>

                                        <?php if(!empty($product_benefits)): ?>
                                        <div class="col-md-4">
                                            <h6 class="text-info mb-3">Benefits</h6>
                                            <ul class="feature-list">
                                                <?php foreach($product_benefits as $benefit): ?>
                                                <li><?php echo htmlspecialchars($benefit); ?></li>
                                                <?php endforeach; ?>
                                            </ul>
                                        </div>
                                        <?php endif; ?>

                                        <?php if(!empty($product_exclusions)): ?>
                                        <div class="col-md-4">
                                            <h6 class="text-danger mb-3">Exclusions</h6>
                                            <ul class="feature-list exclusion-list">
                                                <?php foreach($product_exclusions as $exclusion): ?>
                                                <li><?php echo htmlspecialchars($exclusion); ?></li>
                                                <?php endforeach; ?>
                                            </ul>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Sidebar -->
                        <div class="col-xl-4">
                            <!-- Action Buttons -->
                            <div class="action-buttons no-print">
                                <div class="card info-card">
                                    <div class="card-header">
                                        <h5 class="mb-0">
                                            <i class="ri-tools-line me-2"></i>
                                            Actions
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="d-grid gap-2">
                                            <?php if($quote['effective_status'] === 'ACTIVE' && hasPermission('quotes_convert')): ?>
                                            <a href="convert_quote.php?id=<?php echo $quote['quote_id']; ?>" 
                                               class="btn btn-success">
                                                <i class="ri-exchange-line me-2"></i>
                                                Convert to Policy
                                            </a>
                                            <?php endif; ?>
                                            
                                            <?php if($quote['effective_status'] === 'ACTIVE' && hasPermission('quotes_edit')): ?>
                                            <a href="edit_quote.php?id=<?php echo $quote['quote_id']; ?>" 
                                               class="btn btn-primary">
                                                <i class="ri-edit-line me-2"></i>
                                                Edit Quote
                                            </a>
                                            <?php endif; ?>
                                            
                                            <button type="button" class="btn btn-info" onclick="printQuote()">
                                                <i class="ri-printer-line me-2"></i>
                                                Print Quote
                                            </button>
                                            
                                            <button type="button" class="btn btn-secondary" onclick="emailQuote()">
                                                <i class="ri-mail-line me-2"></i>
                                                Email Quote
                                            </button>
                                            
                                            <a href="list_quotes.php" class="btn btn-outline-secondary">
                                                <i class="ri-arrow-left-line me-2"></i>
                                                Back to Quotes
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Quote Timeline -->
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-time-line me-2"></i>
                                        Quote Timeline
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="timeline-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <strong>Quote Generated</strong>
                                            <small class="text-muted"><?php echo formatDateTime($quote['created_at']); ?></small>
                                        </div>
                                        <small class="text-muted">
                                            Created by <?php echo htmlspecialchars($quote['agent_name']); ?>
                                        </small>
                                    </div>
                                    
                                    <?php if($quote['updated_at'] !== $quote['created_at']): ?>
                                    <div class="timeline-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <strong>Quote Updated</strong>
                                            <small class="text-muted"><?php echo formatDateTime($quote['updated_at']); ?></small>
                                        </div>
                                        <small class="text-muted">Last modification</small>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <div class="timeline-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <strong>Quote Expires</strong>
                                            <small class="text-muted"><?php echo formatDateTime($quote['expires_at']); ?></small>
                                        </div>
                                        <small class="text-muted">
                                            <?php 
                                            if($quote['effective_status'] === 'EXPIRED') {
                                                echo 'Quote has expired';
                                            } else {
                                                echo 'Valid for ' . $quote['validity_days'] . ' days';
                                            }
                                            ?>
                                        </small>
                                    </div>
                                    
                                    <?php if($quote['converted_policy_number']): ?>
                                    <div class="timeline-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <strong>Converted to Policy</strong>
                                            <small class="text-muted"><?php echo formatDateTime($quote['updated_at']); ?></small>
                                        </div>
                                        <small class="text-muted">
                                            Policy: <?php echo htmlspecialchars($quote['converted_policy_number']); ?>
                                        </small>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Agent Information -->
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-user-star-line me-2"></i>
                                        Agent Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex align-items-center mb-3">
                                        <div class="avatar-md me-3">
                                            <span class="avatar-title bg-soft-primary text-primary rounded-circle">
                                                <?php echo strtoupper(substr($quote['agent_name'], 0, 1)); ?>
                                            </span>
                                        </div>
                                        <div>
                                            <h6 class="mb-1"><?php echo htmlspecialchars($quote['agent_name']); ?></h6>
                                            <p class="text-muted mb-0"><?php echo htmlspecialchars($quote['agent_code']); ?></p>
                                        </div>
                                    </div>
                                    
                                    <div class="table-responsive">
                                        <table class="table table-borderless table-sm">
                                            <?php if($quote['agent_phone']): ?>
                                            <tr>
                                                <td class="text-muted">Phone:</td>
                                                <td>
                                                    <a href="tel:<?php echo $quote['agent_phone']; ?>">
                                                        <?php echo htmlspecialchars($quote['agent_phone']); ?>
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php endif; ?>
                                            
                                            <?php if($quote['agent_email']): ?>
                                            <tr>
                                                <td class="text-muted">Email:</td>
                                                <td>
                                                    <a href="mailto:<?php echo $quote['agent_email']; ?>">
                                                        <?php echo htmlspecialchars($quote['agent_email']); ?>
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php endif; ?>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <!-- Insured Details -->
                            <?php if(!empty($insured_details)): ?>
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-shield-user-line me-2"></i>
                                        Insured Details
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php if(isset($insured_details['primary_insured'])): ?>
                                    <div class="mb-4">
                                        <h6 class="text-primary mb-3">Primary Insured</h6>
                                        <div class="row">
                                            <div class="col-12">
                                                <table class="table table-borderless table-sm">
                                                    <tr>
                                                        <td class="text-muted">Name:</td>
                                                        <td class="fw-bold"><?php echo htmlspecialchars($insured_details['primary_insured']['name'] ?? ''); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td class="text-muted">Date of Birth:</td>
                                                        <td>
                                                            <?php 
                                                            $dob = $insured_details['primary_insured']['date_of_birth'] ?? '';
                                                            if($dob) {
                                                                echo formatDate($dob) . ' (' . calculateAge($dob) . ' years)';
                                                            } else {
                                                                echo 'Not specified';
                                                            }
                                                            ?>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td class="text-muted">Gender:</td>
                                                        <td><?php echo ucwords(strtolower($insured_details['primary_insured']['gender'] ?? 'Not specified')); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td class="text-muted">Occupation:</td>
                                                        <td><?php echo htmlspecialchars($insured_details['primary_insured']['occupation'] ?? 'Not specified'); ?></td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>

                                    <?php if(isset($insured_details['dependents']) && !empty($insured_details['dependents'])): ?>
                                    <div>
                                        <h6 class="text-primary mb-3">Dependents (<?php echo count($insured_details['dependents']); ?>)</h6>
                                        <?php foreach($insured_details['dependents'] as $index => $dependent): ?>
                                        <div class="dependent-card">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($dependent['name'] ?? ''); ?></h6>
                                                    <small class="text-muted">
                                                        <?php echo ucwords(strtolower($dependent['relationship'] ?? '')); ?>
                                                    </small>
                                                </div>
                                                <div class="col-md-3">
                                                    <small class="text-muted">DOB:</small><br>
                                                    <span>
                                                        <?php 
                                                        $dep_dob = $dependent['date_of_birth'] ?? '';
                                                        if($dep_dob) {
                                                            echo formatDate($dep_dob) . '<br><small class="text-muted">(' . calculateAge($dep_dob) . ' years)</small>';
                                                        } else {
                                                            echo 'Not specified';
                                                        }
                                                        ?>
                                                    </span>
                                                </div>
                                                <div class="col-md-3">
                                                    <small class="text-muted">Gender:</small><br>
                                                    <span><?php echo ucwords(strtolower($dependent['gender'] ?? 'Not specified')); ?></span>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Risk Assessment -->
                            <?php if(!empty($risk_factors)): ?>
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-shield-cross-line me-2"></i>
                                        Risk Assessment
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <?php if(isset($risk_factors['age'])): ?>
                                        <div class="col-12 mb-3">
                                            <h6 class="text-muted mb-2">Age Factor</h6>
                                            <?php 
                                            $age = $risk_factors['age'];
                                            $age_risk = $age > 60 ? 'high' : ($age > 45 ? 'medium' : 'low');
                                            ?>
                                            <span class="risk-indicator risk-<?php echo $age_risk; ?>">
                                                <?php echo $age; ?> years - <?php echo ucfirst($age_risk); ?> Risk
                                            </span>
                                        </div>
                                        <?php endif; ?>

                                        <?php if(isset($risk_factors['occupation_risk'])): ?>
                                        <div class="col-12 mb-3">
                                            <h6 class="text-muted mb-2">Occupation Risk</h6>
                                            <span class="risk-indicator risk-<?php echo strtolower($risk_factors['occupation_risk']); ?>">
                                                <?php echo ucwords(str_replace('_', ' ', $risk_factors['occupation_risk'])); ?>
                                            </span>
                                        </div>
                                        <?php endif; ?>

                                        <?php if(isset($risk_factors['lifestyle_factors']) && !empty($risk_factors['lifestyle_factors'])): ?>
                                        <div class="col-12 mb-3">
                                            <h6 class="text-muted mb-2">Lifestyle Factors</h6>
                                            <?php foreach($risk_factors['lifestyle_factors'] as $factor): ?>
                                            <span class="badge bg-warning text-dark me-1 mb-1">
                                                <?php echo ucwords(str_replace('_', ' ', $factor)); ?>
                                            </span>
                                            <?php endforeach; ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Special Conditions -->
                            <?php if($quote['special_conditions']): ?>
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-alert-line me-2"></i>
                                        Special Conditions
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($quote['special_conditions'])); ?></p>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        function printQuote() {
            window.print();
        }
        
        function emailQuote() {
            Swal.fire({
                title: 'Email Quote',
                html: `
                    <div class="mb-3">
                        <label for="email_address" class="form-label">Email Address</label>
                        <input type="email" class="form-control" id="email_address" 
                               value="<?php echo htmlspecialchars($quote['customer_email'] ?? ''); ?>" 
                               placeholder="Enter email address">
                    </div>
                    <div class="mb-3">
                        <label for="email_message" class="form-label">Message (Optional)</label>
                        <textarea class="form-control" id="email_message" rows="3" 
                                  placeholder="Add a personal message..."></textarea>
                    </div>
                `,
                showCancelButton: true,
                confirmButtonText: 'Send Email',
                cancelButtonText: 'Cancel',
                preConfirm: () => {
                    const email = document.getElementById('email_address').value;
                    const message = document.getElementById('email_message').value;
                    
                    if (!email) {
                        Swal.showValidationMessage('Please enter an email address');
                        return false;
                    }
                    
                    return { email, message };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire('Info!', 'Email functionality needs to be implemented.', 'info');
                }
            });
        }
        
        // Success message from URL parameter
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('success') === 'created') {
            Swal.fire({
                icon: 'success',
                title: 'Quote Generated!',
                text: 'The insurance quote has been successfully generated.',
                timer: 3000,
                showConfirmButton: false
            });
        }
        
        // Auto-refresh page if quote expires soon (every 5 minutes)
        <?php if($quote['effective_status'] === 'ACTIVE' && $quote['days_to_expire'] <= 1): ?>
        setInterval(() => {
            location.reload();
        }, 300000); // 5 minutes
        <?php endif; ?>
    </script>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>