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

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

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

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

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

function getPolicyStatusClass($status) {
    return match($status) {
        'ACTIVE' => 'success',
        'PENDING' => 'warning',
        'LAPSED' => 'danger',
        'CANCELLED' => 'secondary',
        'SUSPENDED' => 'warning',
        'EXPIRED' => 'danger',
        default => 'secondary'
    };
}

function calculateDaysRemaining($date) {
    $target = new DateTime($date);
    $today = new DateTime('today');
    $diff = $today->diff($target);
    
    if ($target < $today) {
        return -$diff->days; // Negative for overdue
    }
    return $diff->days;
}


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

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

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

// Get policy ID from URL
$policy_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$policy_number = isset($_GET['number']) ? trim($_GET['number']) : '';

if (!$policy_id && !$policy_number) {
    header('Location: list_policies.php?error=invalid_policy');
    exit();
}

// Build the WHERE clause based on what we have
$where_clause = $policy_id ? "p.policy_id = ?" : "p.policy_number = ?";
$param_value = $policy_id ? $policy_id : $policy_number;
$param_type = $policy_id ? "i" : "s";

// Fetch policy details with related information
$sql = "SELECT 
    p.*,
    c.first_name, c.last_name, c.customer_number, c.phone_primary, c.email,
    c.date_of_birth, c.gender, c.national_id, c.address_line1, c.address_line2,
    c.city, c.county, c.postal_code, c.country,
    ip.product_name, ip.product_code, ip.description as product_description,
    ip.key_features, ip.benefits, ip.exclusions as product_exclusions,
    pc.category_name,
    ic.company_name, ic.company_code, ic.contact_person, ic.phone as company_phone,
    u.full_name as agent_name, u.agent_code, u.phone_number as agent_phone, u.email as agent_email,
    q.quote_number,
    CASE 
        WHEN p.expiry_date < CURDATE() AND p.status = 'ACTIVE' THEN 'EXPIRED'
        WHEN p.next_premium_due < CURDATE() AND p.status = 'ACTIVE' THEN 'LAPSED'
        ELSE p.status 
    END as effective_status,
    DATEDIFF(p.expiry_date, CURDATE()) as days_to_expiry,
    DATEDIFF(p.next_premium_due, CURDATE()) as days_to_premium_due
FROM policies p
LEFT JOIN customers c ON p.customer_id = c.customer_id
LEFT JOIN insurance_products ip ON p.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 p.agent_id = u.user_id
LEFT JOIN quotes q ON p.policy_id = q.converted_policy_id
WHERE {$where_clause}";

$stmt = $conn->prepare($sql);
$stmt->bind_param($param_type, $param_value);
$stmt->execute();
$policy = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$policy) {
    header('Location: list_policies.php?error=policy_not_found');
    exit();
}

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

// Parse JSON fields
$covered_members = json_decode($policy['covered_members'], true) ?? [];
$product_features = json_decode($policy['key_features'], true) ?? [];
$product_benefits = json_decode($policy['benefits'], true) ?? [];
$product_exclusions = json_decode($policy['product_exclusions'], true) ?? [];
$policy_exclusions = json_decode($policy['exclusions'], true) ?? [];

// Get recent premium payments
$sql = "SELECT * FROM premium_payments 
        WHERE policy_id = ? 
        ORDER BY payment_date DESC 
        LIMIT 5";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $policy['policy_id']);
$stmt->execute();
$recent_payments = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Get claims for this policy
$sql = "SELECT * FROM claims 
        WHERE policy_id = ? 
        ORDER BY reported_date DESC 
        LIMIT 5";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $policy['policy_id']);
$stmt->execute();
$policy_claims = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Get policy documents
$sql = "SELECT d.*, dc.category_name 
        FROM documents d
        LEFT JOIN document_categories dc ON d.category_id = dc.category_id
        WHERE d.entity_type = 'POLICY' AND d.entity_id = ?
        ORDER BY d.created_at DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $policy['policy_id']);
$stmt->execute();
$policy_documents = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Policy Details - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .policy-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .info-card {
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            border-radius: 15px;
            margin-bottom: 1.5rem;
        }
        
        .info-card .card-header {
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
            border-radius: 15px 15px 0 0;
            padding: 1rem 1.5rem;
        }
        
        .status-badge {
            font-size: 0.875rem;
            padding: 0.5rem 1rem;
            border-radius: 25px;
            font-weight: 600;
        }
        
        .premium-breakdown {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
        }
        
        .premium-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.75rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid rgba(255,255,255,0.2);
        }
        
        .premium-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            font-size: 1.25rem;
            font-weight: 700;
        }
        
        .action-buttons {
            position: sticky;
            top: 20px;
            z-index: 10;
        }
        
        .feature-list {
            list-style: none;
            padding: 0;
        }
        
        .feature-list li {
            padding: 0.5rem 0;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
        }
        
        .feature-list li:last-child {
            border-bottom: none;
        }
        
        .feature-list li::before {
            content: "✓";
            color: #28a745;
            font-weight: bold;
            margin-right: 0.75rem;
            font-size: 1.1rem;
        }
        
        .exclusion-list li::before {
            content: "⨯";
            color: #dc3545;
        }
        
        .renewal-warning {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            color: white;
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 1rem;
        }
        
        .expiry-warning {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 1rem;
        }
        
        .timeline-item {
            padding: 1rem;
            border-left: 3px solid #007bff;
            margin-bottom: 1rem;
            background: #f8f9ff;
            border-radius: 0 10px 10px 0;
        }
        
        .member-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            border-left: 4px solid #007bff;
        }
        
        .payment-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .payment-item:last-child {
            border-bottom: none;
        }
        
        @media print {
            .action-buttons, .no-print { display: none !important; }
            .policy-header { background: #333 !important; }
            .premium-breakdown { background: #555 !important; }
        }
        
        .document-item {
            display: flex;
            align-items: center;
            padding: 0.75rem;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            margin-bottom: 0.5rem;
            transition: all 0.3s ease;
        }
        
        .document-item:hover {
            background: #f8f9fa;
            border-color: #007bff;
        }
        
        .progress-ring {
            width: 60px;
            height: 60px;
            position: relative;
        }
        
        .progress-ring svg {
            width: 100%;
            height: 100%;
            transform: rotate(-90deg);
        }
        
        .progress-ring circle {
            fill: none;
            stroke-width: 4;
            stroke-linecap: round;
        }
        
        .progress-ring .background {
            stroke: #e9ecef;
        }
        
        .progress-ring .progress {
            stroke: #28a745;
            stroke-dasharray: 0 157;
            transition: stroke-dasharray 0.3s ease;
        }
    </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">Policy Details</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_policies.php">Policies</a></li>
                                        <li class="breadcrumb-item active">View Policy</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Policy Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="policy-header">
                                <div class="row align-items-center">
                                    <div class="col-md-6">
                                        <h2 class="mb-2"><?php echo htmlspecialchars($policy['policy_number']); ?></h2>
                                        <p class="mb-0 opacity-75">
                                            Issued on <?php echo formatDateTime($policy['created_at'], 'M j, Y'); ?> | 
                                            Agent: <?php echo htmlspecialchars($policy['agent_name'] . ' (' . $policy['agent_code'] . ')'); ?>
                                        </p>
                                        <?php if($policy['quote_number']): ?>
                                        <p class="mb-0 opacity-75">
                                            Converted from Quote: <?php echo htmlspecialchars($policy['quote_number']); ?>
                                        </p>
                                        <?php endif; ?>
                                    </div>
                                    <div class="col-md-6 text-md-end">
                                        <?php 
                                        $status_class = 'bg-' . getPolicyStatusClass($policy['effective_status']);
                                        ?>
                                        <span class="status-badge <?php echo $status_class; ?>">
                                            <?php echo ucfirst(strtolower($policy['effective_status'])); ?>
                                        </span>
                                        
                                        <div class="mt-2">
                                            <small>Policy Term: <?php echo $policy['policy_term_months']; ?> months</small><br>
                                            <small>Coverage: KSH <?php echo number_format($policy['sum_assured'], 2); ?></small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alerts -->
                    <?php if($policy['effective_status'] === 'ACTIVE' && $policy['days_to_expiry'] <= 30 && $policy['days_to_expiry'] > 0): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="renewal-warning">
                                <div class="d-flex align-items-center">
                                    <i class="ri-time-line fs-4 me-3"></i>
                                    <div>
                                        <h6 class="mb-1">Policy Renewal Due Soon</h6>
                                        <p class="mb-0">
                                            This policy will expire in <?php echo $policy['days_to_expiry']; ?> day(s) 
                                            on <?php echo formatDate($policy['expiry_date']); ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if($policy['effective_status'] === 'EXPIRED'): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="expiry-warning">
                                <div class="d-flex align-items-center">
                                    <i class="ri-alert-triangle-line fs-4 me-3"></i>
                                    <div>
                                        <h6 class="mb-1">Policy Expired</h6>
                                        <p class="mb-0">
                                            This policy expired on <?php echo formatDate($policy['expiry_date']); ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Main Content -->
                        <div class="col-xl-8">
                            <!-- Customer Information -->
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-user-line me-2"></i>
                                        Policyholder Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="d-flex align-items-center mb-3">
                                                <div class="avatar-lg me-3">
                                                    <span class="avatar-title bg-soft-primary text-primary rounded-circle fs-3">
                                                        <?php echo strtoupper(substr($policy['first_name'], 0, 1)); ?>
                                                    </span>
                                                </div>
                                                <div>
                                                    <h5 class="mb-1">
                                                        <?php echo htmlspecialchars($policy['first_name'] . ' ' . $policy['last_name']); ?>
                                                    </h5>
                                                    <p class="text-muted mb-0"><?php echo htmlspecialchars($policy['customer_number']); ?></p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="table-responsive">
                                                <table class="table table-borderless table-sm">
                                                    <?php if($policy['phone_primary']): ?>
                                                    <tr>
                                                        <td class="text-muted">Phone:</td>
                                                        <td>
                                                            <a href="tel:<?php echo $policy['phone_primary']; ?>">
                                                                <?php echo htmlspecialchars($policy['phone_primary']); ?>
                                                            </a>
                                                        </td>
                                                    </tr>
                                                    <?php endif; ?>
                                                    
                                                    <?php if($policy['email']): ?>
                                                    <tr>
                                                        <td class="text-muted">Email:</td>
                                                        <td>
                                                            <a href="mailto:<?php echo $policy['email']; ?>">
                                                                <?php echo htmlspecialchars($policy['email']); ?>
                                                            </a>
                                                        </td>
                                                    </tr>
                                                    <?php endif; ?>
                                                    
                                                    <?php if($policy['date_of_birth']): ?>
                                                    <tr>
                                                        <td class="text-muted">Date of Birth:</td>
                                                        <td>
                                                            <?php echo formatDate($policy['date_of_birth']); ?>
                                                            (<?php echo calculateAge($policy['date_of_birth']); ?> years)
                                                        </td>
                                                    </tr>
                                                    <?php endif; ?>
                                                    
                                                    <?php if($policy['national_id']): ?>
                                                    <tr>
                                                        <td class="text-muted">National ID:</td>
                                                        <td><?php echo htmlspecialchars($policy['national_id']); ?></td>
                                                    </tr>
                                                    <?php endif; ?>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <?php if($policy['address_line1']): ?>
                                    <div class="row mt-3">
                                        <div class="col-12">
                                            <h6 class="text-muted mb-2">Address</h6>
                                            <p class="mb-0">
                                                <?php 
                                                $address_parts = array_filter([
                                                    $policy['address_line1'],
                                                    $policy['address_line2'],
                                                    $policy['city'],
                                                    $policy['county'],
                                                    $policy['postal_code'],
                                                    $policy['country']
                                                ]);
                                                echo htmlspecialchars(implode(', ', $address_parts));
                                                ?>
                                            </p>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Policy Details -->
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-file-text-line me-2"></i>
                                        Policy Details
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <table class="table table-borderless table-sm">
                                                <tr>
                                                    <td class="text-muted">Policy Number:</td>
                                                    <td class="fw-bold"><?php echo htmlspecialchars($policy['policy_number']); ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Policy Type:</td>
                                                    <td><?php echo ucwords(str_replace('_', ' ', $policy['policy_type'])); ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Coverage Type:</td>
                                                    <td><?php echo ucwords(str_replace('_', ' ', $policy['coverage_type'])); ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Sum Assured:</td>
                                                    <td class="fw-bold text-success">KSH <?php echo number_format($policy['sum_assured'], 2); ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Premium Frequency:</td>
                                                    <td><?php echo ucwords(str_replace('_', ' ', strtolower($policy['premium_frequency']))); ?></td>
                                                </tr>
                                            </table>
                                        </div>
                                        <div class="col-md-6">
                                            <table class="table table-borderless table-sm">
                                                <tr>
                                                    <td class="text-muted">Inception Date:</td>
                                                    <td><?php echo formatDate($policy['inception_date']); ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Expiry Date:</td>
                                                    <td><?php echo formatDate($policy['expiry_date']); ?></td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Next Premium Due:</td>
                                                    <td>
                                                        <?php 
                                                        $due_class = $policy['days_to_premium_due'] < 0 ? 'text-danger' : ($policy['days_to_premium_due'] <= 7 ? 'text-warning' : '');
                                                        ?>
                                                        <span class="<?php echo $due_class; ?>">
                                                            <?php echo formatDate($policy['next_premium_due']); ?>
                                                        </span>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Grace Period:</td>
                                                    <td><?php echo $policy['grace_period_days']; ?> days</td>
                                                </tr>
                                                <tr>
                                                    <td class="text-muted">Free Look Period:</td>
                                                    <td><?php echo $policy['free_look_period_days']; ?> days</td>
                                                </tr>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Covered Members -->
                            <?php if(!empty($covered_members)): ?>
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-team-line me-2"></i>
                                        Covered Members
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php if(isset($covered_members['primary_insured'])): ?>
                                    <div class="mb-4">
                                        <h6 class="text-primary mb-3">Primary Insured</h6>
                                        <div class="member-card">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($covered_members['primary_insured']['name'] ?? ''); ?></h6>
                                                    <small class="text-muted">Primary Policyholder</small>
                                                </div>
                                                <div class="col-md-3">
                                                    <small class="text-muted">DOB:</small><br>
                                                    <span>
                                                        <?php 
                                                        $dob = $covered_members['primary_insured']['date_of_birth'] ?? '';
                                                        if($dob) {
                                                            echo formatDate($dob);
                                                        } else {
                                                            echo 'Not specified';
                                                        }
                                                        ?>
                                                    </span>
                                                </div>
                                                <div class="col-md-3">
                                                    <small class="text-muted">Gender:</small><br>
                                                    <span><?php echo ucwords(strtolower($covered_members['primary_insured']['gender'] ?? 'Not specified')); ?></span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>

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

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

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

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

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

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

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

                            <!-- Recent Premium Payments -->
                            <?php if(!empty($recent_payments)): ?>
                            <div class="card info-card">
                                <div class="card-header">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="mb-0">
                                            <i class="ri-money-dollar-circle-line me-2"></i>
                                            Recent Premium Payments
                                        </h5>
                                        <a href="payments/list_payments.php?policy_id=<?php echo $policy['policy_id']; ?>" class="btn btn-sm btn-outline-primary">
                                            View All
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body p-0">
                                    <?php foreach($recent_payments as $payment): ?>
                                    <div class="payment-item">
                                        <div>
                                            <div class="fw-medium"><?php echo htmlspecialchars($payment['payment_number']); ?></div>
                                            <small class="text-muted">
                                                <?php echo formatDate($payment['payment_date']); ?> | 
                                                <?php echo ucwords(str_replace('_', ' ', $payment['payment_method'])); ?>
                                            </small>
                                        </div>
                                        <div class="text-end">
                                            <div class="fw-bold text-success">KSH <?php echo number_format($payment['total_amount'], 2); ?></div>
                                            <?php 
                                            $payment_status_class = match($payment['status']) {
                                                'COMPLETED' => 'success',
                                                'PENDING' => 'warning',
                                                'FAILED' => 'danger',
                                                'REFUNDED' => 'info',
                                                default => 'secondary'
                                            };
                                            ?>
                                            <span class="badge bg-<?php echo $payment_status_class; ?> badge-sm">
                                                <?php echo ucfirst(strtolower($payment['status'])); ?>
                                            </span>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Claims History -->
                            <?php if(!empty($policy_claims)): ?>
                            <div class="card info-card">
                                <div class="card-header">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="mb-0">
                                            <i class="ri-hand-heart-line me-2"></i>
                                            Claims History
                                        </h5>
                                        <a href="claims/list_claims.php?policy_id=<?php echo $policy['policy_id']; ?>" class="btn btn-sm btn-outline-primary">
                                            View All
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body p-0">
                                    <?php foreach($policy_claims as $claim): ?>
                                    <div class="payment-item">
                                        <div>
                                            <div class="fw-medium"><?php echo htmlspecialchars($claim['claim_number']); ?></div>
                                            <small class="text-muted">
                                                <?php echo formatDate($claim['reported_date']); ?> | 
                                                <?php echo ucwords(str_replace('_', ' ', $claim['claim_type'])); ?>
                                            </small>
                                        </div>
                                        <div class="text-end">
                                            <div class="fw-bold">KSH <?php echo number_format($claim['claimed_amount'], 2); ?></div>
                                            <?php 
                                            $claim_status_class = match($claim['status']) {
                                                'SUBMITTED' => 'info',
                                                'UNDER_INVESTIGATION' => 'warning',
                                                'APPROVED' => 'success',
                                                'REJECTED' => 'danger',
                                                'PAID' => 'success',
                                                default => 'secondary'
                                            };
                                            ?>
                                            <span class="badge bg-<?php echo $claim_status_class; ?> badge-sm">
                                                <?php echo ucfirst(str_replace('_', ' ', strtolower($claim['status']))); ?>
                                            </span>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>

                        <!-- Sidebar -->
                        <div class="col-xl-4">
                            <!-- Action Buttons -->
                            <div class="action-buttons no-print">
                                <div class="card info-card">
                                    <div class="card-header">
                                        <h5 class="mb-0">
                                            <i class="ri-tools-line me-2"></i>
                                            Actions
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="d-grid gap-2">
                                            <?php if($policy['effective_status'] === 'ACTIVE'): ?>
                                            
                                            <?php if(hasPermission('payments_record')): ?>
                                            <a href="payments/record_payment.php?policy_id=<?php echo $policy['policy_id']; ?>" 
                                               class="btn btn-success">
                                                <i class="ri-money-dollar-circle-line me-2"></i>
                                                Record Payment
                                            </a>
                                            <?php endif; ?>
                                            
                                            <?php if(hasPermission('claims_submit')): ?>
                                            <a href="claims/submit_claim.php?policy_id=<?php echo $policy['policy_id']; ?>" 
                                               class="btn btn-warning">
                                                <i class="ri-hand-heart-line me-2"></i>
                                                Submit Claim
                                            </a>
                                            <?php endif; ?>
                                            
                                            <?php if(hasPermission('policies_endorse')): ?>
                                            <a href="policies/endorse_policy.php?id=<?php echo $policy['policy_id']; ?>" 
                                               class="btn btn-info">
                                                <i class="ri-edit-line me-2"></i>
                                                Endorse Policy
                                            </a>
                                            <?php endif; ?>
                                            
                                            <?php if(hasPermission('policies_renew')): ?>
                                            <a href="policies/renew_policy.php?id=<?php echo $policy['policy_id']; ?>" 
                                               class="btn btn-primary">
                                                <i class="ri-refresh-line me-2"></i>
                                                Renew Policy
                                            </a>
                                            <?php endif; ?>
                                            
                                            <?php endif; ?>
                                            
                                            <button type="button" class="btn btn-secondary" onclick="printPolicy()">
                                                <i class="ri-printer-line me-2"></i>
                                                Print Policy
                                            </button>
                                            
                                            <button type="button" class="btn btn-outline-secondary" onclick="downloadCertificate()">
                                                <i class="ri-download-line me-2"></i>
                                                Download Certificate
                                            </button>
                                            
                                            <hr>
                                            
                                            <a href="list_policies.php" class="btn btn-outline-secondary">
                                                <i class="ri-arrow-left-line me-2"></i>
                                                Back to Policies
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Premium Summary -->
                            <div class="premium-breakdown">
                                <h5 class="mb-3">
                                    <i class="ri-money-dollar-circle-line me-2"></i>
                                    Premium Summary
                                </h5>
                                
                                <div class="premium-item">
                                    <span>Sum Assured:</span>
                                    <span>KSH <?php echo number_format($policy['sum_assured'], 2); ?></span>
                                </div>
                                
                                <div class="premium-item">
                                    <span>Premium Amount:</span>
                                    <span>KSH <?php echo number_format($policy['premium_amount'], 2); ?></span>
                                </div>
                                
                                <div class="premium-item">
                                    <span>Policy Fee:</span>
                                    <span>KSH <?php echo number_format($policy['policy_fee'], 2); ?></span>
                                </div>
                                
                                <div class="premium-item">
                                    <span>Stamp Duty:</span>
                                    <span>KSH <?php echo number_format($policy['stamp_duty'], 2); ?></span>
                                </div>
                                
                                <div class="premium-item">
                                    <span><strong>TOTAL PREMIUM:</strong></span>
                                    <span><strong>KSH <?php 
                                        $total_premium = $policy['premium_amount'] + $policy['policy_fee'] + $policy['stamp_duty'];
                                        echo number_format($total_premium, 2); 
                                    ?></strong></span>
                                </div>
                                
                                <div class="mt-3 text-center">
                                    <small class="opacity-75">
                                        <?php echo ucwords(str_replace('_', ' ', strtolower($policy['premium_frequency']))); ?> Premium
                                    </small>
                                </div>
                                
                                <?php if($policy['commission_amount'] > 0): ?>
                                <div class="mt-3 pt-2" style="border-top: 1px solid rgba(255,255,255,0.2);">
                                    <div class="d-flex justify-content-between">
                                        <small>Agent Commission:</small>
                                        <small>KSH <?php echo number_format($policy['commission_amount'], 2); ?></small>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Policy Timeline -->
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-time-line me-2"></i>
                                        Policy Timeline
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="timeline-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <strong>Policy Issued</strong>
                                            <small class="text-muted"><?php echo formatDateTime($policy['created_at']); ?></small>
                                        </div>
                                        <small class="text-muted">
                                            Issued by <?php echo htmlspecialchars($policy['agent_name']); ?>
                                        </small>
                                    </div>
                                    
                                    <div class="timeline-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <strong>Policy Effective</strong>
                                            <small class="text-muted"><?php echo formatDateTime($policy['inception_date']); ?></small>
                                        </div>
                                        <small class="text-muted">Coverage started</small>
                                    </div>
                                    
                                    <div class="timeline-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <strong>Next Premium Due</strong>
                                            <small class="text-muted"><?php echo formatDateTime($policy['next_premium_due']); ?></small>
                                        </div>
                                        <small class="text-muted">
                                            <?php 
                                            if($policy['days_to_premium_due'] < 0) {
                                                echo 'Overdue by ' . abs($policy['days_to_premium_due']) . ' days';
                                            } else {
                                                echo 'Due in ' . $policy['days_to_premium_due'] . ' days';
                                            }
                                            ?>
                                        </small>
                                    </div>
                                    
                                    <div class="timeline-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <strong>Policy Expires</strong>
                                            <small class="text-muted"><?php echo formatDateTime($policy['expiry_date']); ?></small>
                                        </div>
                                        <small class="text-muted">
                                            <?php 
                                            if($policy['days_to_expiry'] < 0) {
                                                echo 'Expired ' . abs($policy['days_to_expiry']) . ' days ago';
                                            } else {
                                                echo 'Expires in ' . $policy['days_to_expiry'] . ' days';
                                            }
                                            ?>
                                        </small>
                                    </div>
                                </div>
                            </div>

                            <!-- Company Information -->
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-building-line me-2"></i>
                                        Insurance Company
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="text-center mb-3">
                                        <h6 class="mb-1"><?php echo htmlspecialchars($policy['company_name']); ?></h6>
                                        <p class="text-muted mb-0"><?php echo htmlspecialchars($policy['company_code']); ?></p>
                                    </div>
                                    
                                    <?php if($policy['contact_person']): ?>
                                    <div class="mb-2">
                                        <small class="text-muted">Contact Person:</small><br>
                                        <span><?php echo htmlspecialchars($policy['contact_person']); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if($policy['company_phone']): ?>
                                    <div class="mb-2">
                                        <small class="text-muted">Phone:</small><br>
                                        <a href="tel:<?php echo $policy['company_phone']; ?>" class="text-decoration-none">
                                            <?php echo htmlspecialchars($policy['company_phone']); ?>
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>

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

                            <!-- Documents -->
                            <?php if(!empty($policy_documents)): ?>
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-file-text-line me-2"></i>
                                        Policy Documents
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php foreach($policy_documents as $document): ?>
                                    <div class="document-item">
                                        <div class="me-3">
                                            <i class="ri-file-text-line fs-4 text-primary"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <div class="fw-medium"><?php echo htmlspecialchars($document['document_name']); ?></div>
                                            <small class="text-muted">
                                                <?php echo htmlspecialchars($document['category_name']); ?> | 
                                                <?php echo formatDate($document['created_at']); ?>
                                            </small>
                                        </div>
                                        <div>
                                            <a href="download_document.php?id=<?php echo $document['document_id']; ?>" 
                                               class="btn btn-sm btn-outline-primary">
                                                <i class="ri-download-line"></i>
                                            </a>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        function printPolicy() {
            window.print();
        }
        
        function downloadCertificate() {
            Swal.fire({
                title: 'Download Certificate',
                text: 'Generate and download policy certificate?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Download',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Redirect to certificate generation
                    window.location.href = 'generate_certificate.php?policy_id=<?php echo $policy['policy_id']; ?>';
                }
            });
        }
        
        // Success message from URL parameter
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('success') === 'converted') {
            Swal.fire({
                icon: 'success',
                title: 'Policy Created!',
                text: 'The quote has been successfully converted to a policy.',
                timer: 3000,
                showConfirmButton: false
            });
        }
        
        // Auto-refresh page if policy expires soon (every 30 minutes)
        <?php if($policy['effective_status'] === 'ACTIVE' && $policy['days_to_expiry'] <= 1): ?>
        setInterval(() => {
            location.reload();
        }, 1800000); // 30 minutes
        <?php endif; ?>
        
        // Initialize tooltips
        document.addEventListener('DOMContentLoaded', function() {
            // Add any initialization code here
            console.log('Policy view loaded successfully');
        });
    </script>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>