<?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 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 generatePolicyNumber($prefix = 'POL') {
    $timestamp = date('ymdHis');
    $random = substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 4);
    return strtoupper($prefix . $timestamp . $random);
}

function logActivity($action, $module, $record_id = null, $record_type = null, $old_values = null, $new_values = null) {
    global $conn;
    
    if (!isset($_SESSION['user_id'])) {
        return false;
    }
    
    try {
    $ip_address = $_SERVER['REMOTE_ADDR'];
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $session_id = session_id();
    
    // Assign JSON-encoded values to variables
    $old_values_json = $old_values ? json_encode($old_values) : null;
    $new_values_json = $new_values ? json_encode($new_values) : null;
    
    $sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, old_values, new_values, ip_address, user_agent, session_id) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ississssss", 
        $_SESSION['user_id'], 
        $action, 
        $module, 
        $record_id, 
        $record_type,
        $old_values_json, // Use variable instead of ternary result
        $new_values_json, // Use variable instead of ternary result
        $ip_address,
        substr($user_agent, 0, 500),
        $session_id
    );
    
    $stmt->execute();
    $stmt->close();
    
    return true;
} catch (Exception $e) {
    error_log("Activity log 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();
}

// Check permission
if (!hasPermission('quotes_convert')) {
    header('Location: view_quote.php?id=' . ($_GET['id'] ?? 0) . '&error=no_permission');
    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();
}

$errors = [];
$success_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Start transaction
        $conn->begin_transaction();
        
        // Get quote details
        $sql = "SELECT q.*, c.customer_id, ip.product_id, ip.company_id 
                FROM quotes q
                LEFT JOIN customers c ON q.customer_id = c.customer_id
                LEFT JOIN insurance_products ip ON q.product_id = ip.product_id
                WHERE q.quote_id = ? AND q.status = 'ACTIVE'";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $quote_id);
        $stmt->execute();
        $quote = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if (!$quote) {
            throw new Exception("Quote not found or not active");
        }
        
        // Check if quote has expired
        if (strtotime($quote['expires_at']) < time()) {
            throw new Exception("Quote has expired and cannot be converted");
        }
        
        // Get form data
        $inception_date = $_POST['inception_date'] ?? date('Y-m-d');
        $policy_term_months = (int)($_POST['policy_term_months'] ?? 12);
        $special_conditions = trim($_POST['special_conditions'] ?? '');
        $underwriting_required = isset($_POST['underwriting_required']) ? 1 : 0;
        
        // Calculate expiry date
        $expiry_date = date('Y-m-d', strtotime($inception_date . ' + ' . $policy_term_months . ' months'));
        
        // Generate policy number
        $policy_number = generatePolicyNumber();
        
        // Insert policy
        $sql = "INSERT INTO policies (
            policy_number, customer_id, product_id, company_id, agent_id,
            policy_type, coverage_type, sum_assured, premium_amount, premium_frequency,
            policy_term_months, inception_date, expiry_date, next_premium_due,
            commission_rate, commission_amount, policy_fee, stamp_duty,
            covered_members, special_conditions, exclusions, benefits,
            status, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ACTIVE', NOW())";
        
        $stmt = $conn->prepare($sql);
        
        // Calculate next premium due date based on frequency
        $next_premium_due = match($quote['premium_frequency']) {
            'MONTHLY' => date('Y-m-d', strtotime($inception_date . ' + 1 month')),
            'QUARTERLY' => date('Y-m-d', strtotime($inception_date . ' + 3 months')),
            'SEMI_ANNUAL' => date('Y-m-d', strtotime($inception_date . ' + 6 months')),
            default => date('Y-m-d', strtotime($inception_date . ' + 1 year'))
        };
        
        // Determine coverage type from quote
        $coverage_type = 'HEALTH'; // Default, should be determined from product
        
        // Calculate commission rate as a separate variable
        $commission_rate = ($quote['commission_amount'] > 0 && $quote['final_premium'] > 0) 
            ? ($quote['commission_amount'] / $quote['final_premium'] * 100) 
            : 0;
        
        $stmt->bind_param("siiiissddsissssdssssss",
            $policy_number,
            $quote['customer_id'],
            $quote['product_id'],
            $quote['company_id'],
            $quote['agent_id'],
            $quote['quote_type'],
            $coverage_type,
            $quote['coverage_amount'],
            $quote['final_premium'],
            $quote['premium_frequency'],
            $policy_term_months,
            $inception_date,
            $expiry_date,
            $next_premium_due,
            $commission_rate,
            //($quote['commission_amount'] / $quote['final_premium'] * 100), // Commission rate
            $quote['commission_amount'],
            $quote['policy_fee'],
            $quote['stamp_duty'],
            $quote['insured_details'],
            $special_conditions,
            $quote['exclusions'],
            $quote['benefits']
        );
        
        $stmt->execute();
        $policy_id = $conn->insert_id;
        $stmt->close();
        
        // Update quote status to CONVERTED
        $sql = "UPDATE quotes SET status = 'CONVERTED', converted_policy_id = ?, updated_at = NOW() WHERE quote_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $policy_id, $quote_id);
        $stmt->execute();
        $stmt->close();
        
        // Create underwriting application if required
        if ($underwriting_required) {
            $application_number = 'UW' . date('ymdHis') . sprintf('%04d', $policy_id);
            
            $sql = "INSERT INTO underwriting_applications (
                application_number, quote_id, customer_id, product_id, agent_id,
                application_type, sum_assured, premium_amount, status, submitted_at
            ) VALUES (?, ?, ?, ?, ?, 'NEW', ?, ?, 'SUBMITTED', NOW())";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("siiidd", 
                $application_number, $quote_id, $quote['customer_id'], 
                $quote['product_id'], $quote['agent_id'],
                $quote['coverage_amount'], $quote['final_premium']
            );
            $stmt->execute();
            $stmt->close();
        }
        
        // Log the conversion activity
        logActivity('CONVERT', 'QUOTE_TO_POLICY', $quote_id, 'QUOTE', 
            ['quote_status' => 'ACTIVE'], 
            ['policy_id' => $policy_id, 'policy_number' => $policy_number]
        );
        
        // Commit transaction
        $conn->commit();
        
        // Redirect to policy view
        header("Location: policies/view_policy.php?id={$policy_id}&success=converted");
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $errors[] = $e->getMessage();
        error_log("Policy conversion error: " . $e->getMessage());
    }
}

// Fetch quote details for display
$sql = "SELECT 
    q.*,
    c.first_name, c.last_name, c.customer_number, c.phone_primary, c.email,
    ip.product_name, ip.product_code, ip.policy_term_months as default_term,
    pc.category_name,
    ic.company_name,
    u.full_name as agent_name, u.agent_code
FROM quotes q
LEFT JOIN customers c ON q.customer_id = c.customer_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 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 if quote can be converted
$can_convert = true;
$conversion_errors = [];

if ($quote['status'] !== 'ACTIVE') {
    $can_convert = false;
    $conversion_errors[] = 'Quote is not active';
}

if (strtotime($quote['expires_at']) < time()) {
    $can_convert = false;
    $conversion_errors[] = 'Quote has expired';
}

if ($quote['converted_policy_id']) {
    $can_convert = false;
    $conversion_errors[] = 'Quote has already been converted to a policy';
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Convert Quote to Policy - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .conversion-header {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .quote-summary {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .form-card {
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            border-radius: 15px;
            margin-bottom: 1.5rem;
        }
        
        .form-card .card-header {
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
            border-radius: 15px 15px 0 0;
            padding: 1rem 1.5rem;
        }
        
        .premium-highlight {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 1rem;
            text-align: center;
        }
        
        .warning-box {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .error-box {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 2rem;
        }
        
        .step {
            display: flex;
            align-items: center;
            margin: 0 1rem;
        }
        
        .step-number {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 0.5rem;
        }
        
        .step.active .step-number {
            background: #28a745;
            color: white;
        }
        
        .step.completed .step-number {
            background: #6c757d;
            color: white;
        }
        
        .step.inactive .step-number {
            background: #e9ecef;
            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">Convert Quote to Policy</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"><a href="view_quote.php?id=<?php echo $quote_id; ?>">View Quote</a></li>
                                        <li class="breadcrumb-item active">Convert to Policy</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Conversion Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="conversion-header">
                                <div class="row align-items-center">
                                    <div class="col-md-8">
                                        <h2 class="mb-2">Convert Quote to Policy</h2>
                                        <p class="mb-0 opacity-75">
                                            Quote: <?php echo htmlspecialchars($quote['quote_number']); ?> | 
                                            Customer: <?php echo htmlspecialchars($quote['first_name'] . ' ' . $quote['last_name']); ?>
                                        </p>
                                    </div>
                                    <div class="col-md-4 text-md-end">
                                        <div class="premium-highlight">
                                            <h5 class="mb-1">Total Premium</h5>
                                            <h3 class="mb-0">KSH <?php echo number_format($quote['final_premium'], 2); ?></h3>
                                            <small><?php echo ucwords(str_replace('_', ' ', strtolower($quote['premium_frequency']))); ?></small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Step Indicator -->
                    <div class="step-indicator">
                        <div class="step completed">
                            <div class="step-number">1</div>
                            <span>Quote Generated</span>
                        </div>
                        <div class="step active">
                            <div class="step-number">2</div>
                            <span>Convert to Policy</span>
                        </div>
                        <div class="step inactive">
                            <div class="step-number">3</div>
                            <span>Policy Active</span>
                        </div>
                    </div>

                    <!-- Error Messages -->
                    <?php if (!empty($errors)): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="error-box">
                                <h6 class="text-danger mb-2">
                                    <i class="ri-error-warning-line me-2"></i>
                                    Conversion Errors
                                </h6>
                                <ul class="mb-0 text-danger">
                                    <?php foreach ($errors as $error): ?>
                                    <li><?php echo htmlspecialchars($error); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Conversion Errors -->
                    <?php if (!$can_convert): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="error-box">
                                <h6 class="text-danger mb-2">
                                    <i class="ri-close-circle-line me-2"></i>
                                    Cannot Convert Quote
                                </h6>
                                <ul class="mb-3 text-danger">
                                    <?php foreach ($conversion_errors as $error): ?>
                                    <li><?php echo htmlspecialchars($error); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                                <a href="view_quote.php?id=<?php echo $quote_id; ?>" class="btn btn-secondary">
                                    <i class="ri-arrow-left-line me-2"></i>
                                    Back to Quote
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php else: ?>

                    <div class="row">
                        <!-- Main Form -->
                        <div class="col-xl-8">
                            <!-- Quote Summary -->
                            <div class="quote-summary">
                                <h5 class="mb-3">Quote Summary</h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <table class="table table-borderless table-sm">
                                            <tr>
                                                <td class="text-muted">Quote Number:</td>
                                                <td class="fw-bold"><?php echo htmlspecialchars($quote['quote_number']); ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Product:</td>
                                                <td><?php echo htmlspecialchars($quote['product_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Company:</td>
                                                <td><?php echo htmlspecialchars($quote['company_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Coverage:</td>
                                                <td>KSH <?php echo number_format($quote['coverage_amount'], 2); ?></td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div class="col-md-6">
                                        <table class="table table-borderless table-sm">
                                            <tr>
                                                <td class="text-muted">Customer:</td>
                                                <td><?php echo htmlspecialchars($quote['first_name'] . ' ' . $quote['last_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Agent:</td>
                                                <td><?php echo htmlspecialchars($quote['agent_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Quote Expires:</td>
                                                <td><?php echo formatDateTime($quote['expires_at']); ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Generated:</td>
                                                <td><?php echo formatDateTime($quote['created_at']); ?></td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <!-- Conversion Form -->
                            <form method="POST" id="conversionForm">
                                <div class="card form-card">
                                    <div class="card-header">
                                        <h5 class="mb-0">
                                            <i class="ri-settings-3-line me-2"></i>
                                            Policy Details
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="inception_date" class="form-label">Policy Inception Date <span class="text-danger">*</span></label>
                                                <input type="date" class="form-control" id="inception_date" name="inception_date" 
                                                       value="<?php echo date('Y-m-d'); ?>" 
                                                       min="<?php echo date('Y-m-d'); ?>" 
                                                       max="<?php echo date('Y-m-d', strtotime('+30 days')); ?>" 
                                                       required>
                                                <div class="form-text">Policy will become effective from this date</div>
                                            </div>
                                            
                                            <div class="col-md-6 mb-3">
                                                <label for="policy_term_months" class="form-label">Policy Term (Months) <span class="text-danger">*</span></label>
                                                <select class="form-select" id="policy_term_months" name="policy_term_months" required>
                                                    <option value="12" <?php echo ($quote['default_term'] == 12) ? 'selected' : ''; ?>>12 Months</option>
                                                    <option value="6" <?php echo ($quote['default_term'] == 6) ? 'selected' : ''; ?>>6 Months</option>
                                                    <option value="24" <?php echo ($quote['default_term'] == 24) ? 'selected' : ''; ?>>24 Months</option>
                                                    <option value="36" <?php echo ($quote['default_term'] == 36) ? 'selected' : ''; ?>>36 Months</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-12 mb-3">
                                                <label for="special_conditions" class="form-label">Special Conditions / Notes</label>
                                                <textarea class="form-control" id="special_conditions" name="special_conditions" rows="4" 
                                                          placeholder="Enter any special conditions or notes for this policy..."><?php echo htmlspecialchars($quote['special_conditions'] ?? ''); ?></textarea>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-12">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="underwriting_required" name="underwriting_required">
                                                    <label class="form-check-label" for="underwriting_required">
                                                        Underwriting Required
                                                    </label>
                                                    <div class="form-text">Check if this policy requires underwriting review before activation</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Terms and Conditions -->
                                <div class="card form-card">
                                    <div class="card-header">
                                        <h5 class="mb-0">
                                            <i class="ri-file-text-line me-2"></i>
                                            Terms and Conditions
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="warning-box">
                                            <h6 class="text-warning mb-2">
                                                <i class="ri-alert-line me-2"></i>
                                                Important Notice
                                            </h6>
                                            <ul class="mb-0 text-muted">
                                                <li>By converting this quote to a policy, you confirm that all information provided is accurate</li>
                                                <li>The policy will be subject to the terms and conditions of the selected insurance product</li>
                                                <li>Premium payments must be made according to the selected frequency</li>
                                                <li>This action cannot be undone once the policy is created</li>
                                            </ul>
                                        </div>

                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="confirm_conversion" required>
                                            <label class="form-check-label" for="confirm_conversion">
                                                I confirm that I want to convert this quote to an active insurance policy <span class="text-danger">*</span>
                                            </label>
                                        </div>
                                    </div>
                                </div>

                                <!-- Action Buttons -->
                                <div class="d-flex justify-content-between">
                                    <a href="view_quote.php?id=<?php echo $quote_id; ?>" class="btn btn-outline-secondary">
                                        <i class="ri-arrow-left-line me-2"></i>
                                        Back to Quote
                                    </a>
                                    
                                    <button type="submit" class="btn btn-success btn-lg" id="convertBtn">
                                        <i class="ri-exchange-line me-2"></i>
                                        Convert to Policy
                                    </button>
                                </div>
                            </form>
                        </div>

                        <!-- Sidebar -->
                        <div class="col-xl-4">
                            <!-- Premium Breakdown -->
                            <div class="card form-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-money-dollar-circle-line me-2"></i>
                                        Premium Breakdown
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Base Premium:</span>
                                        <span>KSH <?php echo number_format($quote['base_premium'], 2); ?></span>
                                    </div>
                                    
                                    <?php if($quote['risk_premium'] > 0): ?>
                                    <div class="d-flex justify-content-between mb-2">
                                        <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="d-flex justify-content-between mb-2">
                                        <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="d-flex justify-content-between mb-2">
                                        <span>Discount:</span>
                                        <span class="text-success">- KSH <?php echo number_format($quote['discount_amount'], 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Policy Fee:</span>
                                        <span>KSH <?php echo number_format($quote['policy_fee'], 2); ?></span>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>Stamp Duty:</span>
                                        <span>KSH <?php echo number_format($quote['stamp_duty'], 2); ?></span>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between mb-2">
                                        <span>VAT (16%):</span>
                                        <span>KSH <?php echo number_format($quote['tax_amount'], 2); ?></span>
                                    </div>
                                    
                                    <hr>
                                    
                                    <div class="d-flex justify-content-between mb-3">
                                        <strong>Total Premium:</strong>
                                        <strong class="text-success">KSH <?php echo number_format($quote['final_premium'], 2); ?></strong>
                                    </div>
                                    
                                    <div class="text-center">
                                        <small class="text-muted">
                                            <?php echo ucwords(str_replace('_', ' ', strtolower($quote['premium_frequency']))); ?> Payment
                                        </small>
                                    </div>
                                    
                                    <?php if($quote['commission_amount'] > 0): ?>
                                    <hr>
                                    <div class="d-flex justify-content-between">
                                        <small class="text-muted">Agent Commission:</small>
                                        <small class="text-muted">KSH <?php echo number_format($quote['commission_amount'], 2); ?></small>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Important Notes -->
                            <div class="card form-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-information-line me-2"></i>
                                        Important Notes
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-info">
                                        <h6 class="alert-heading mb-2">Policy Activation</h6>
                                        <small>
                                            • Policy becomes effective from the inception date<br>
                                            • First premium payment is due immediately<br>
                                            • Grace period: 30 days from due date<br>
                                            • Free look period: 15 days from policy start
                                        </small>
                                    </div>
                                    
                                    <div class="alert alert-warning">
                                        <h6 class="alert-heading mb-2">Next Steps</h6>
                                        <small>
                                            After conversion:<br>
                                            • Policy documents will be generated<br>
                                            • Customer will receive confirmation<br>
                                            • First premium payment should be collected<br>
                                            • Certificate will be issued
                                        </small>
                                    </div>
                                </div>
                            </div>

                            <!-- Contact Information -->
                            <div class="card form-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-user-line me-2"></i>
                                        Customer Contact
                                    </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['first_name'], 0, 1)); ?>
                                            </span>
                                        </div>
                                        <div>
                                            <h6 class="mb-1"><?php echo htmlspecialchars($quote['first_name'] . ' ' . $quote['last_name']); ?></h6>
                                            <p class="text-muted mb-0"><?php echo htmlspecialchars($quote['customer_number']); ?></p>
                                        </div>
                                    </div>
                                    
                                    <?php if($quote['phone_primary']): ?>
                                    <div class="mb-2">
                                        <small class="text-muted">Phone:</small><br>
                                        <a href="tel:<?php echo $quote['phone_primary']; ?>" class="text-decoration-none">
                                            <?php echo htmlspecialchars($quote['phone_primary']); ?>
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if($quote['email']): ?>
                                    <div class="mb-2">
                                        <small class="text-muted">Email:</small><br>
                                        <a href="mailto:<?php echo $quote['email']; ?>" class="text-decoration-none">
                                            <?php echo htmlspecialchars($quote['email']); ?>
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php endif; ?>

                </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>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('conversionForm');
            const convertBtn = document.getElementById('convertBtn');
            const confirmCheckbox = document.getElementById('confirm_conversion');
            const inceptionDateInput = document.getElementById('inception_date');
            const policyTermSelect = document.getElementById('policy_term_months');
            
            // Enable/disable convert button based on confirmation checkbox
            function updateConvertButton() {
                convertBtn.disabled = !confirmCheckbox.checked;
            }
            
            confirmCheckbox.addEventListener('change', updateConvertButton);
            updateConvertButton(); // Initial state
            
            // Calculate and display expiry date
            function updateExpiryDate() {
                const inceptionDate = new Date(inceptionDateInput.value);
                const termMonths = parseInt(policyTermSelect.value);
                
                if (inceptionDate && termMonths) {
                    const expiryDate = new Date(inceptionDate);
                    expiryDate.setMonth(expiryDate.getMonth() + termMonths);
                    
                    const expiryDateStr = expiryDate.toLocaleDateString('en-US', {
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric'
                    });
                    
                    // Update expiry display if element exists
                    const expiryDisplay = document.getElementById('expiry_display');
                    if (expiryDisplay) {
                        expiryDisplay.textContent = `Policy will expire on: ${expiryDateStr}`;
                    }
                }
            }
            
            inceptionDateInput.addEventListener('change', updateExpiryDate);
            policyTermSelect.addEventListener('change', updateExpiryDate);
            updateExpiryDate(); // Initial calculation
            
            // Form submission with confirmation
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                
                Swal.fire({
                    title: 'Convert Quote to Policy?',
                    html: `
                        <div class="text-start">
                            <p><strong>Quote:</strong> <?php echo htmlspecialchars($quote['quote_number']); ?></p>
                            <p><strong>Customer:</strong> <?php echo htmlspecialchars($quote['first_name'] . ' ' . $quote['last_name']); ?></p>
                            <p><strong>Premium:</strong> KSH <?php echo number_format($quote['final_premium'], 2); ?></p>
                            <p><strong>Inception Date:</strong> <span id="confirm_inception"></span></p>
                            <hr>
                            <p class="text-warning mb-0">
                                <i class="ri-alert-line me-1"></i>
                                This action cannot be undone. The quote will be converted to an active policy.
                            </p>
                        </div>
                    `,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#28a745',
                    cancelButtonColor: '#6c757d',
                    confirmButtonText: 'Yes, Convert to Policy',
                    cancelButtonText: 'Cancel',
                    showLoaderOnConfirm: true,
                    preConfirm: () => {
                        // Update confirmation dialog with current inception date
                        document.getElementById('confirm_inception').textContent = 
                            new Date(inceptionDateInput.value).toLocaleDateString('en-US', {
                                year: 'numeric',
                                month: 'long',
                                day: 'numeric'
                            });
                        
                        return true;
                    },
                    allowOutsideClick: () => !Swal.isLoading()
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Show loading state
                        convertBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Converting...';
                        convertBtn.disabled = true;
                        
                        // Submit the form
                        form.submit();
                    }
                });
            });
            
            // Validate inception date
            inceptionDateInput.addEventListener('change', function() {
                const selectedDate = new Date(this.value);
                const today = new Date();
                const maxDate = new Date();
                maxDate.setDate(today.getDate() + 30);
                
                if (selectedDate < today) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Invalid Date',
                        text: 'Policy inception date cannot be in the past.',
                        confirmButtonColor: '#28a745'
                    });
                    this.value = today.toISOString().split('T')[0];
                } else if (selectedDate > maxDate) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Invalid Date',
                        text: 'Policy inception date cannot be more than 30 days in the future.',
                        confirmButtonColor: '#28a745'
                    });
                    this.value = maxDate.toISOString().split('T')[0];
                }
            });
            
            // Auto-save form data to localStorage (optional)
            const formFields = ['inception_date', 'policy_term_months', 'special_conditions'];
            
            // Save form data
            function saveFormData() {
                const formData = {};
                formFields.forEach(field => {
                    const element = document.getElementById(field);
                    if (element) {
                        formData[field] = element.value;
                    }
                });
                localStorage.setItem('conversion_form_<?php echo $quote_id; ?>', JSON.stringify(formData));
            }
            
            // Load form data
            function loadFormData() {
                const savedData = localStorage.getItem('conversion_form_<?php echo $quote_id; ?>');
                if (savedData) {
                    try {
                        const formData = JSON.parse(savedData);
                        formFields.forEach(field => {
                            const element = document.getElementById(field);
                            if (element && formData[field] !== undefined) {
                                element.value = formData[field];
                            }
                        });
                    } catch (e) {
                        console.error('Error loading saved form data:', e);
                    }
                }
            }
            
            // Clear saved data on successful submission
            function clearSavedData() {
                localStorage.removeItem('conversion_form_<?php echo $quote_id; ?>');
            }
            
            // Load saved data on page load
            loadFormData();
            
            // Save data on form field changes
            formFields.forEach(field => {
                const element = document.getElementById(field);
                if (element) {
                    element.addEventListener('change', saveFormData);
                    element.addEventListener('input', saveFormData);
                }
            });
            
            // Clear saved data if form submission is successful
            form.addEventListener('submit', function() {
                setTimeout(clearSavedData, 1000);
            });
        });
        
        // Show success message if redirected with success parameter
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('success')) {
            Swal.fire({
                icon: 'success',
                title: 'Conversion Started!',
                text: 'The quote conversion process has been initiated.',
                timer: 3000,
                showConfirmButton: false
            });
        }
        
        // Countdown timer for quote expiry (if quote expires within 24 hours)
        <?php 
        $time_to_expiry = strtotime($quote['expires_at']) - time();
        if ($time_to_expiry > 0 && $time_to_expiry <= 86400): // 24 hours
        ?>
        let timeToExpiry = <?php echo $time_to_expiry; ?>;
        
        function updateCountdown() {
            if (timeToExpiry <= 0) {
                Swal.fire({
                    icon: 'error',
                    title: 'Quote Expired!',
                    text: 'This quote has expired and can no longer be converted to a policy.',
                    allowOutsideClick: false,
                    showCancelButton: false,
                    confirmButtonText: 'Go Back'
                }).then(() => {
                    window.location.href = 'view_quote.php?id=<?php echo $quote_id; ?>';
                });
                return;
            }
            
            const hours = Math.floor(timeToExpiry / 3600);
            const minutes = Math.floor((timeToExpiry % 3600) / 60);
            const seconds = timeToExpiry % 60;
            
            const countdownElement = document.getElementById('countdown_timer');
            if (countdownElement) {
                countdownElement.textContent = `${hours}h ${minutes}m ${seconds}s`;
            }
            
            timeToExpiry--;
        }
        
        // Update countdown every second
        setInterval(updateCountdown, 1000);
        updateCountdown(); // Initial call
        <?php endif; ?>
    </script>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>