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

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

//include 'layouts/dbconn.php';

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

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

// Pagination setup
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$records_per_page = 20;
$offset = ($page - 1) * $records_per_page;

// Search and filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$agent_filter = isset($_GET['agent']) ? (int)$_GET['agent'] : '';
$product_filter = isset($_GET['product']) ? (int)$_GET['product'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build WHERE clause
$where_conditions = [];
$params = [];
$param_types = '';

// Role-based filtering - agents can only see their own quotes unless they have broader permissions
if ($user_role === 'Insurance Agent' && !hasPermission('quotes_view_all')) {
    $where_conditions[] = "q.agent_id = ?";
    $params[] = $agent_id;
    $param_types .= 'i';
}

if (!empty($search)) {
    $where_conditions[] = "(q.quote_number LIKE ? OR c.first_name LIKE ? OR c.last_name LIKE ? OR l.first_name LIKE ? OR l.last_name LIKE ? OR ip.product_name LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param, $search_param, $search_param]);
    $param_types .= 'ssssss';
}

if (!empty($status_filter)) {
    $where_conditions[] = "q.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if (!empty($agent_filter)) {
    $where_conditions[] = "q.agent_id = ?";
    $params[] = $agent_filter;
    $param_types .= 'i';
}

if (!empty($product_filter)) {
    $where_conditions[] = "q.product_id = ?";
    $params[] = $product_filter;
    $param_types .= 'i';
}

if (!empty($date_from)) {
    $where_conditions[] = "DATE(q.created_at) >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if (!empty($date_to)) {
    $where_conditions[] = "DATE(q.created_at) <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count for pagination
$count_sql = "SELECT COUNT(*) as total 
              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 users u ON q.agent_id = u.user_id
              $where_clause";

if (!empty($params)) {
    $count_stmt = $conn->prepare($count_sql);
    if (!empty($param_types)) {
        $count_stmt->bind_param($param_types, ...$params);
    }
    $count_stmt->execute();
    $total_records = $count_stmt->get_result()->fetch_assoc()['total'];
    $count_stmt->close();
} else {
    $total_records = $conn->query($count_sql)->fetch_assoc()['total'];
}

$total_pages = ceil($total_records / $records_per_page);

// Main query to fetch quotes
$sql = "SELECT 
    q.quote_id,
    q.quote_number,
    q.quote_type,
    q.coverage_amount,
    q.total_premium,
    q.final_premium,
    q.premium_frequency,
    q.status,
    q.expires_at,
    q.created_at,
    q.converted_policy_id,
    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,
    ip.product_name,
    ip.product_code,
    pc.category_name,
    ic.company_name,
    u.full_name as agent_name,
    u.agent_code,
    CASE 
        WHEN q.expires_at < NOW() THEN 'EXPIRED'
        ELSE q.status 
    END as effective_status,
    DATEDIFF(q.expires_at, NOW()) as days_to_expire
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
$where_clause
ORDER BY q.created_at DESC
LIMIT ? OFFSET ?";

// Add pagination parameters
$params[] = $records_per_page;
$params[] = $offset;
$param_types .= 'ii';

$stmt = $conn->prepare($sql);
if (!empty($param_types)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

// Get agents for filter dropdown (based on permissions)
//if (hasPermission('quotes_view_all')) {
    $agents_sql = "SELECT user_id, full_name, agent_code FROM users WHERE agent_code IS NOT NULL AND status = 'ACTIVE' ORDER BY full_name";
//} else {
    $agents_sql = "SELECT user_id, full_name, agent_code FROM users WHERE user_id = ? ORDER BY full_name";
//}
$agents_stmt = $conn->prepare($agents_sql);
//if (!hasPermission('quotes_view_all')) {
    $agents_stmt->bind_param("i", $agent_id);
//}
$agents_stmt->execute();
$agents_result = $agents_stmt->get_result();

// Get products for filter dropdown
$products_sql = "SELECT product_id, product_name, product_code FROM insurance_products WHERE is_active = 1 ORDER BY product_name";
$products_result = $conn->query($products_sql);

// Get quote statistics
$stats_sql = "SELECT 
    COUNT(*) as total_quotes,
    SUM(CASE WHEN status = 'ACTIVE' THEN 1 ELSE 0 END) as active_quotes,
    SUM(CASE WHEN status = 'CONVERTED' THEN 1 ELSE 0 END) as converted_quotes,
    SUM(CASE WHEN expires_at < NOW() AND status = 'ACTIVE' THEN 1 ELSE 0 END) as expired_quotes,
    SUM(total_premium) as total_quoted_premium,
    AVG(total_premium) as avg_premium
FROM quotes q " . ($user_role === 'Insurance Agent' && !hasPermission('quotes_view_all') ? "WHERE q.agent_id = $agent_id" : "");
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Insurance Quotes - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css">
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <!-- Flatpickr CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        .quote-card {
            transition: all 0.3s ease;
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            border-radius: 15px;
        }
        
        .quote-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .status-badge {
            font-size: 0.75rem;
            padding: 0.35rem 0.65rem;
            border-radius: 20px;
            font-weight: 600;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            border: none;
        }
        
        .filter-card {
            background: #f8f9fa;
            border-radius: 15px;
            border: none;
        }
        
        .quote-header {
            border-bottom: 1px solid #eee;
            padding-bottom: 1rem;
            margin-bottom: 1rem;
        }
        
        .premium-amount {
            font-size: 1.25rem;
            font-weight: 700;
            color: #28a745;
        }
        
        .expiry-warning {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            color: white;
            padding: 0.5rem;
            border-radius: 10px;
            font-size: 0.875rem;
        }
        
        .btn-action {
            padding: 0.25rem 0.75rem;
            font-size: 0.875rem;
            border-radius: 20px;
        }
        
        .customer-info {
            background: #f8f9ff;
            border-radius: 8px;
            padding: 0.75rem;
        }
        
        .quote-meta {
            font-size: 0.875rem;
            color: #6c757d;
        }
    </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">Insurance Quotes</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">Products & Quotes</li>
                                        <li class="breadcrumb-item active">Quotes</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Stats Overview -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium mb-0" style="opacity: 0.8;">Total Quotes</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['total_quotes']); ?></h4>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm rounded-circle bg-white bg-opacity-25">
                                                <span class="avatar-title rounded-circle">
                                                    <i class="ri-file-text-line fs-4"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card bg-success text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium mb-0" style="opacity: 0.8;">Active Quotes</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['active_quotes']); ?></h4>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm rounded-circle bg-white bg-opacity-25">
                                                <span class="avatar-title rounded-circle">
                                                    <i class="ri-check-line fs-4"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card bg-info text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium mb-0" style="opacity: 0.8;">Converted</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['converted_quotes']); ?></h4>
                                            <p class="mb-0 small">
                                                <?php 
                                                $conversion_rate = $stats['total_quotes'] > 0 ? 
                                                    round(($stats['converted_quotes'] / $stats['total_quotes']) * 100, 1) : 0;
                                                echo $conversion_rate . '% conversion';
                                                ?>
                                            </p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm rounded-circle bg-white bg-opacity-25">
                                                <span class="avatar-title rounded-circle">
                                                    <i class="ri-exchange-line fs-4"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card bg-warning text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium mb-0" style="opacity: 0.8;">Quoted Premium</p>
                                            <h4 class="mb-0">KSH <?php echo number_format($stats['total_quoted_premium'], 0); ?></h4>
                                            <p class="mb-0 small">
                                                Avg: KSH <?php echo number_format($stats['avg_premium'], 0); ?>
                                            </p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm rounded-circle bg-white bg-opacity-25">
                                                <span class="avatar-title rounded-circle">
                                                    <i class="ri-money-dollar-circle-line fs-4"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters and Actions -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card filter-card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3 align-items-end">
                                        <div class="col-md-2">
                                            <label class="form-label">Search Quotes</label>
                                            <input type="text" class="form-control" name="search" 
                                                   placeholder="Quote number, customer..." 
                                                   value="<?php echo htmlspecialchars($search); ?>">
                                        </div>
                                        
                                        <div class="col-md-2">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status">
                                                <option value="">All Status</option>
                                                <option value="DRAFT" <?php echo ($status_filter === 'DRAFT') ? 'selected' : ''; ?>>Draft</option>
                                                <option value="PENDING" <?php echo ($status_filter === 'PENDING') ? 'selected' : ''; ?>>Pending</option>
                                                <option value="ACTIVE" <?php echo ($status_filter === 'ACTIVE') ? 'selected' : ''; ?>>Active</option>
                                                <option value="EXPIRED" <?php echo ($status_filter === 'EXPIRED') ? 'selected' : ''; ?>>Expired</option>
                                                <option value="CONVERTED" <?php echo ($status_filter === 'CONVERTED') ? 'selected' : ''; ?>>Converted</option>
                                                <option value="REJECTED" <?php echo ($status_filter === 'REJECTED') ? 'selected' : ''; ?>>Rejected</option>
                                            </select>
                                        </div>
                                        
                                        
                                        <div class="col-md-2">
                                            <label class="form-label">Agent</label>
                                            <select class="form-select" name="agent">
                                                <option value="">All Agents</option>
                                                <?php 
                                                mysqli_data_seek($agents_result, 0);
                                                while($agent = $agents_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $agent['user_id']; ?>" 
                                                            <?php echo ($agent_filter == $agent['user_id']) ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($agent['full_name'] . ' (' . $agent['agent_code'] . ')'); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-2">
                                            <label class="form-label">Product</label>
                                            <select class="form-select" name="product">
                                                <option value="">All Products</option>
                                                <?php while($product = $products_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $product['product_id']; ?>" 
                                                            <?php echo ($product_filter == $product['product_id']) ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($product['product_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-2">
                                            <label class="form-label">Date From</label>
                                            <input type="date" class="form-control" name="date_from" 
                                                   value="<?php echo htmlspecialchars($date_from); ?>">
                                        </div>
                                        
                                        <div class="col-md-2">
                                            <label class="form-label">Date To</label>
                                            <input type="date" class="form-control" name="date_to" 
                                                   value="<?php echo htmlspecialchars($date_to); ?>">
                                        </div>
                                        
                                        <div class="col-md-12">
                                            <div class="d-flex gap-2">
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="ri-search-line me-1"></i> Search
                                                </button>
                                                <a href="list_quotes.php" class="btn btn-secondary">
                                                    <i class="ri-refresh-line me-1"></i> Reset
                                                </a>
                                                
                                                <a href="new_quote.php" class="btn btn-success">
                                                    <i class="ri-add-line me-1"></i> New Quote
                                                </a>
                                                
                                                <button type="button" class="btn btn-info" onclick="exportQuotes()">
                                                    <i class="ri-download-line me-1"></i> Export
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quotes Grid -->
                    <div class="row">
                        <?php if($result->num_rows > 0): ?>
                            <?php while($quote = $result->fetch_assoc()): ?>
                            <div class="col-xl-6 col-lg-6 mb-4">
                                <div class="card quote-card h-100">
                                    <div class="card-body">
                                        <!-- Quote Header -->
                                        <div class="quote-header">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <h5 class="card-title mb-1">
                                                        <a href="view_quote.php?id=<?php echo $quote['quote_id']; ?>" 
                                                           class="text-decoration-none">
                                                            <?php echo htmlspecialchars($quote['quote_number']); ?>
                                                        </a>
                                                    </h5>
                                                    <p class="quote-meta mb-0">
                                                        Created: <?php echo date('M j, Y g:i A', strtotime($quote['created_at'])); ?>
                                                    </p>
                                                </div>
                                                <div class="text-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>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Customer Information -->
                                        <div class="customer-info mb-3">
                                            <div class="d-flex align-items-center mb-2">
                                                <div class="avatar-sm me-2">
                                                    <span class="avatar-title bg-soft-primary text-primary rounded-circle">
                                                        <?php 
                                                        $name = $quote['customer_first_name'];
                                                        echo strtoupper(substr($name, 0, 1)); 
                                                        ?>
                                                    </span>
                                                </div>
                                                <div>
                                                    <h6 class="mb-0">
                                                        <?php echo htmlspecialchars($quote['customer_first_name'] . ' ' . $quote['customer_last_name']); ?>
                                                    </h6>
                                                    <p class="quote-meta mb-0">
                                                        <?php if($quote['customer_reference']): ?>
                                                            <?php echo htmlspecialchars($quote['customer_reference']); ?>
                                                        <?php endif; ?>
                                                        <?php if($quote['customer_phone']): ?>
                                                            | 📞 <?php echo htmlspecialchars($quote['customer_phone']); ?>
                                                        <?php endif; ?>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Product and Coverage Details -->
                                        <div class="row mb-3">
                                            <div class="col-12">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div>
                                                        <h6 class="text-primary mb-1"><?php echo htmlspecialchars($quote['product_name']); ?></h6>
                                                        <p class="quote-meta mb-1"><?php echo htmlspecialchars($quote['company_name']); ?></p>
                                                        <span class="badge bg-soft-info text-info">
                                                            <?php echo htmlspecialchars($quote['category_name']); ?>
                                                        </span>
                                                        <span class="badge bg-soft-secondary text-secondary ms-1">
                                                            <?php echo ucwords(str_replace('_', ' ', $quote['quote_type'])); ?>
                                                        </span>
                                                    </div>
                                                    <div class="text-end">
                                                        <div class="premium-amount">
                                                            KSH <?php echo number_format($quote['final_premium'], 2); ?>
                                                        </div>
                                                        <p class="quote-meta mb-0">
                                                            <?php echo ucwords(str_replace('_', ' ', strtolower($quote['premium_frequency']))); ?>
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Coverage Amount -->
                                        <div class="mb-3">
                                            <div class="d-flex justify-content-between">
                                                <span class="quote-meta">Coverage Amount:</span>
                                                <span class="fw-bold">KSH <?php echo number_format($quote['coverage_amount'], 2); ?></span>
                                            </div>
                                        </div>
                                        
                                        <!-- Agent Information -->
                                        <div class="mb-3">
                                            <div class="d-flex justify-content-between">
                                                <span class="quote-meta">Agent:</span>
                                                <span><?php echo htmlspecialchars($quote['agent_name']); ?> 
                                                      (<?php echo htmlspecialchars($quote['agent_code']); ?>)</span>
                                            </div>
                                        </div>
                                        
                                        <!-- Expiry Information -->
                                        <?php if($quote['effective_status'] === 'ACTIVE'): ?>
                                        <div class="mb-3">
                                            <?php if($quote['days_to_expire'] <= 7 && $quote['days_to_expire'] > 0): ?>
                                            <div class="expiry-warning">
                                                <i class="ri-time-line me-2"></i>
                                                Expires in <?php echo $quote['days_to_expire']; ?> day(s) 
                                                on <?php echo date('M j, Y', strtotime($quote['expires_at'])); ?>
                                            </div>
                                            <?php else: ?>
                                            <div class="quote-meta">
                                                <i class="ri-calendar-line me-1"></i>
                                                Expires: <?php echo date('M j, Y', strtotime($quote['expires_at'])); ?>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <!-- Card Actions -->
                                    <div class="card-footer bg-transparent border-top-0">
                                        <div class="d-flex gap-2 justify-content-between">
                                            <a href="view_quote.php?id=<?php echo $quote['quote_id']; ?>" 
                                               class="btn btn-outline-primary btn-action">
                                                <i class="ri-eye-line me-1"></i> View
                                            </a>
                                            
                                            <?php if($quote['effective_status'] === 'ACTIVE' && hasPermission('quotes_edit')): ?>
                                            <a href="edit_quote.php?id=<?php echo $quote['quote_id']; ?>" 
                                               class="btn btn-outline-secondary btn-action">
                                                <i class="ri-edit-line me-1"></i> Edit
                                            </a>
                                            <?php endif; ?>
                                            
                                            <?php if($quote['effective_status'] === 'ACTIVE' && hasPermission('quotes_convert')): ?>
                                            <a href="convert_quote.php?id=<?php echo $quote['quote_id']; ?>" 
                                               class="btn btn-outline-success btn-action">
                                                <i class="ri-exchange-line me-1"></i> Convert
                                            </a>
                                            <?php endif; ?>
                                            
                                            <div class="dropdown">
                                                <button class="btn btn-outline-info btn-action dropdown-toggle" 
                                                        type="button" data-bs-toggle="dropdown">
                                                    <i class="ri-more-line"></i>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <li>
                                                        <a class="dropdown-item" href="print_quote.php?id=<?php echo $quote['quote_id']; ?>" target="_blank">
                                                            <i class="ri-printer-line me-2"></i> Print Quote
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="email_quote.php?id=<?php echo $quote['quote_id']; ?>">
                                                            <i class="ri-mail-line me-2"></i> Email Quote
                                                        </a>
                                                    </li>
                                                    <?php if($quote['effective_status'] === 'ACTIVE'): ?>
                                                    <li>
                                                        <a class="dropdown-item" href="duplicate_quote.php?id=<?php echo $quote['quote_id']; ?>">
                                                            <i class="ri-file-copy-line me-2"></i> Duplicate
                                                        </a>
                                                    </li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li>
                                                        <a class="dropdown-item text-warning" 
                                                           href="javascript:void(0)" 
                                                           onclick="extendQuote(<?php echo $quote['quote_id']; ?>)">
                                                            <i class="ri-time-line me-2"></i> Extend Validity
                                                        </a>
                                                    </li>
                                                    <?php endif; ?>
                                                    <?php if(hasPermission('quotes_delete')): ?>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li>
                                                        <a class="dropdown-item text-danger" 
                                                           href="javascript:void(0)" 
                                                           onclick="deleteQuote(<?php echo $quote['quote_id']; ?>, '<?php echo htmlspecialchars($quote['quote_number']); ?>')">
                                                            <i class="ri-delete-bin-line me-2"></i> Delete
                                                        </a>
                                                    </li>
                                                    <?php endif; ?>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-body text-center py-5">
                                        <div class="mb-3">
                                            <i class="ri-file-text-line display-4 text-muted"></i>
                                        </div>
                                        <h5 class="mb-3">No Quotes Found</h5>
                                        <p class="text-muted mb-3">No insurance quotes match your current filters.</p>
                                        
                                        <a href="new_quote.php" class="btn btn-primary">
                                            <i class="ri-add-line me-1"></i> Generate First Quote
                                        </a>
                                        
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Pagination -->
                    <?php if($total_pages > 1): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <p class="text-muted mb-0">
                                                Showing <?php echo $offset + 1; ?> to 
                                                <?php echo min($offset + $records_per_page, $total_records); ?> 
                                                of <?php echo $total_records; ?> quotes
                                            </p>
                                        </div>
                                        
                                        <nav aria-label="Page navigation">
                                            <ul class="pagination mb-0">
                                                <?php if($page > 1): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=1<?php echo buildQueryString(['page']); ?>">
                                                        First
                                                    </a>
                                                </li>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $page-1; ?><?php echo buildQueryString(['page']); ?>">
                                                        Previous
                                                    </a>
                                                </li>
                                                <?php endif; ?>
                                                
                                                <?php 
                                                $start_page = max(1, $page - 2);
                                                $end_page = min($total_pages, $page + 2);
                                                
                                                for($i = $start_page; $i <= $end_page; $i++): 
                                                ?>
                                                <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                                    <a class="page-link" href="?page=<?php echo $i; ?><?php echo buildQueryString(['page']); ?>">
                                                        <?php echo $i; ?>
                                                    </a>
                                                </li>
                                                <?php endfor; ?>
                                                
                                                <?php if($page < $total_pages): ?>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $page+1; ?><?php echo buildQueryString(['page']); ?>">
                                                        Next
                                                    </a>
                                                </li>
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=<?php echo $total_pages; ?><?php echo buildQueryString(['page']); ?>">
                                                        Last
                                                    </a>
                                                </li>
                                                <?php endif; ?>
                                            </ul>
                                        </nav>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

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

    <!-- Extend Quote Modal -->
    <div class="modal fade" id="extendQuoteModal" tabindex="-1" aria-labelledby="extendQuoteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="extendQuoteModalLabel">Extend Quote Validity</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="extendQuoteForm">
                    <div class="modal-body">
                        <input type="hidden" id="extend_quote_id" name="quote_id">
                        <div class="mb-3">
                            <label for="new_expiry_date" class="form-label">New Expiry Date</label>
                            <input type="date" class="form-control" id="new_expiry_date" name="new_expiry_date" required>
                        </div>
                        <div class="mb-3">
                            <label for="extend_reason" class="form-label">Reason for Extension</label>
                            <textarea class="form-control" id="extend_reason" name="reason" rows="3" 
                                      placeholder="Enter reason for extending quote validity" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-warning">Extend Quote</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <!-- Flatpickr JS -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize Select2 for dropdowns
            $('.form-select').select2({
                theme: 'bootstrap-5',
                width: '100%'
            });
            
            // Initialize date picker
            flatpickr('[type="date"]', {
                dateFormat: "Y-m-d",
                allowInput: true
            });
            
            // Animate cards on load
            $('.quote-card').each(function(index) {
                $(this).css('opacity', '0').delay(index * 50).animate({
                    opacity: 1
                }, 300);
            });
            
            // Handle extend quote form submission
            $('#extendQuoteForm').on('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                
                fetch('extend_quote.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Quote Extended',
                            text: data.message,
                            confirmButtonText: 'OK'
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: data.message,
                            confirmButtonText: 'OK'
                        });
                    }
                    $('#extendQuoteModal').modal('hide');
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'An error occurred while extending the quote.',
                        confirmButtonText: 'OK'
                    });
                    $('#extendQuoteModal').modal('hide');
                });
            });
        });
        
        function extendQuote(quoteId) {
            $('#extend_quote_id').val(quoteId);
            
            // Set minimum date to tomorrow
            const tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);
            const minDate = tomorrow.toISOString().split('T')[0];
            $('#new_expiry_date').attr('min', minDate);
            
            // Set default date to 30 days from today
            const defaultDate = new Date();
            defaultDate.setDate(defaultDate.getDate() + 30);
            const defaultDateStr = defaultDate.toISOString().split('T')[0];
            $('#new_expiry_date').val(defaultDateStr);
            
            $('#extendQuoteModal').modal('show');
        }
        
        function deleteQuote(quoteId, quoteNumber) {
            Swal.fire({
                title: 'Delete Quote?',
                text: `Are you sure you want to delete quote ${quoteNumber}? This action cannot be undone.`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Send delete request
                    fetch('delete_quote.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            quote_id: quoteId
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Deleted!',
                                text: data.message,
                                confirmButtonText: 'OK'
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: data.message,
                                confirmButtonText: 'OK'
                            });
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'An error occurred while deleting the quote.',
                            confirmButtonText: 'OK'
                        });
                    });
                }
            });
        }
        
        function exportQuotes() {
            // Get current filter parameters
            const params = new URLSearchParams(window.location.search);
            params.set('export', 'true');
            
            Swal.fire({
                title: 'Export Quotes',
                text: 'Choose export format:',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Excel (.xlsx)',
                cancelButtonText: 'CSV (.csv)',
                showDenyButton: true,
                denyButtonText: 'PDF Report'
            }).then((result) => {
                if (result.isConfirmed) {
                    params.set('format', 'excel');
                    window.open(`export_quotes.php?${params.toString()}`, '_blank');
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    params.set('format', 'csv');
                    window.open(`export_quotes.php?${params.toString()}`, '_blank');
                } else if (result.isDenied) {
                    params.set('format', 'pdf');
                    window.open(`export_quotes.php?${params.toString()}`, '_blank');
                }
            });
        }
    </script>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>