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

// Essential utility functions
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;
    }
    
    if (isset($_SESSION['role_name']) && $_SESSION['role_name'] === 'Super Admin') {
        return true;
    }
    
    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;
    }
}

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

// Check permission
if (!hasPermission('policies_view')) {
    header('Location: view_policy.php?id=' . ($_GET['policy_id'] ?? 0) . '&error=no_permission');
    exit();
}

$policy_id = isset($_GET['policy_id']) ? (int)$_GET['policy_id'] : 0;

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

// Fetch policy details for certificate
$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,
    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
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
WHERE p.policy_id = ?";

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

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

// Parse covered members
$covered_members = json_decode($policy['covered_members'], true) ?? [];

$conn->close();

// Set content type for PDF download
if (isset($_GET['download']) && $_GET['download'] === 'pdf') {
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="Policy_Certificate_' . $policy['policy_number'] . '.pdf"');
    // In a real implementation, you would use a PDF library like TCPDF or DOMPDF here
    // For now, we'll just redirect back with a message
    header('Location: view_policy.php?id=' . $policy_id . '&message=pdf_generation_not_implemented');
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Insurance Certificate - <?php echo htmlspecialchars($policy['policy_number']); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @page {
            size: A4;
            margin: 0.5in;
        }
        
        body {
            font-family: 'Times New Roman', serif;
            line-height: 1.4;
            color: #333;
        }
        
        .certificate-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 40px;
            border: 3px solid #2c5aa0;
            border-radius: 15px;
            background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        
        .certificate-header {
            text-align: center;
            margin-bottom: 40px;
            border-bottom: 2px solid #2c5aa0;
            padding-bottom: 20px;
        }
        
        .company-logo {
            width: 80px;
            height: 80px;
            margin: 0 auto 20px;
            background: #2c5aa0;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 2rem;
            font-weight: bold;
        }
        
        .certificate-title {
            font-size: 2.5rem;
            font-weight: bold;
            color: #2c5aa0;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 2px;
        }
        
        .certificate-subtitle {
            font-size: 1.2rem;
            color: #666;
            margin-bottom: 20px;
        }
        
        .policy-details {
            background: #ffffff;
            border: 1px solid #dee2e6;
            border-radius: 10px;
            padding: 25px;
            margin: 30px 0;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px dotted #ccc;
        }
        
        .detail-row:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }
        
        .detail-label {
            font-weight: bold;
            color: #2c5aa0;
            flex: 0 0 40%;
        }
        
        .detail-value {
            flex: 1;
            text-align: right;
        }
        
        .coverage-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin: 25px 0;
        }
        
        .signature-section {
            margin-top: 50px;
            display: flex;
            justify-content: space-between;
            align-items: end;
        }
        
        .signature-block {
            text-align: center;
            width: 200px;
        }
        
        .signature-line {
            border-top: 2px solid #333;
            margin-bottom: 10px;
            height: 60px;
            display: flex;
            align-items: end;
            justify-content: center;
        }
        
        .watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 8rem;
            color: rgba(44, 90, 160, 0.1);
            z-index: -1;
            font-weight: bold;
            pointer-events: none;
        }
        
        .certificate-footer {
            text-align: center;
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #dee2e6;
            font-size: 0.9rem;
            color: #666;
        }
        
        .no-print {
            margin: 20px 0;
            text-align: center;
        }
        
        @media print {
            .no-print { display: none !important; }
            body { margin: 0; }
            .certificate-container { 
                border: 2px solid #000; 
                margin: 0;
                box-shadow: none;
            }
        }
        
        .qr-code {
            width: 80px;
            height: 80px;
            border: 1px solid #ccc;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.7rem;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="watermark">ULTRASURE</div>
    
    <div class="no-print">
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <a href="view_policy.php?id=<?php echo $policy_id; ?>" class="btn btn-secondary">
                    <i class="ri-arrow-left-line me-2"></i>Back to Policy
                </a>
                <div>
                    <button onclick="window.print()" class="btn btn-primary me-2">
                        <i class="ri-printer-line me-2"></i>Print Certificate
                    </button>
                    <a href="?policy_id=<?php echo $policy_id; ?>&download=pdf" class="btn btn-success">
                        <i class="ri-download-line me-2"></i>Download PDF
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="certificate-container">
        <!-- Header -->
        <div class="certificate-header">
            <div class="company-logo">
                U
            </div>
            <div class="certificate-title">Certificate of Insurance</div>
            <div class="certificate-subtitle">This is to certify that the policy described below has been issued</div>
        </div>

        <!-- Company Information -->
        <div class="text-center mb-4">
            <h4 class="text-primary mb-1"><?php echo htmlspecialchars($policy['company_name']); ?></h4>
            <p class="mb-0">Licensed Insurance Company</p>
        </div>

        <!-- Policy Details -->
        <div class="policy-details">
            <div class="detail-row">
                <span class="detail-label">Policy Number:</span>
                <span class="detail-value fw-bold"><?php echo htmlspecialchars($policy['policy_number']); ?></span>
            </div>
            
            <div class="detail-row">
                <span class="detail-label">Policyholder:</span>
                <span class="detail-value"><?php echo htmlspecialchars($policy['first_name'] . ' ' . $policy['last_name']); ?></span>
            </div>
            
            <div class="detail-row">
                <span class="detail-label">Customer Number:</span>
                <span class="detail-value"><?php echo htmlspecialchars($policy['customer_number']); ?></span>
            </div>
            
            <div class="detail-row">
                <span class="detail-label">Product:</span>
                <span class="detail-value"><?php echo htmlspecialchars($policy['product_name']); ?></span>
            </div>
            
            <div class="detail-row">
                <span class="detail-label">Coverage Type:</span>
                <span class="detail-value"><?php echo ucwords(str_replace('_', ' ', $policy['coverage_type'])); ?></span>
            </div>
            
            <div class="detail-row">
                <span class="detail-label">Policy Type:</span>
                <span class="detail-value"><?php echo ucwords(str_replace('_', ' ', $policy['policy_type'])); ?></span>
            </div>
            
            <div class="detail-row">
                <span class="detail-label">Effective Date:</span>
                <span class="detail-value"><?php echo formatDate($policy['inception_date']); ?></span>
            </div>
            
            <div class="detail-row">
                <span class="detail-label">Expiry Date:</span>
                <span class="detail-value"><?php echo formatDate($policy['expiry_date']); ?></span>
            </div>
            
            <div class="detail-row">
                <span class="detail-label">Sum Assured:</span>
                <span class="detail-value fw-bold text-success">KSH <?php echo number_format($policy['sum_assured'], 2); ?></span>
            </div>
            
            <div class="detail-row">
                <span class="detail-label">Premium Amount:</span>
                <span class="detail-value">KSH <?php echo number_format($policy['premium_amount'], 2); ?></span>
            </div>
            
            <div class="detail-row">
                <span class="detail-label">Premium Frequency:</span>
                <span class="detail-value"><?php echo ucwords(str_replace('_', ' ', strtolower($policy['premium_frequency']))); ?></span>
            </div>
        </div>

        <!-- Coverage Information -->
        <div class="coverage-section">
            <h5 class="text-primary mb-3">Coverage Information</h5>
            
            <?php if(!empty($covered_members)): ?>
            <div class="mb-3">
                <strong>Covered Members:</strong>
                <ul class="mt-2 mb-0">
                    <?php if(isset($covered_members['primary_insured'])): ?>
                    <li><strong>Primary:</strong> <?php echo htmlspecialchars($covered_members['primary_insured']['name'] ?? 'Not specified'); ?></li>
                    <?php endif; ?>
                    
                    <?php if(isset($covered_members['dependents']) && !empty($covered_members['dependents'])): ?>
                    <?php foreach($covered_members['dependents'] as $dependent): ?>
                    <li><strong>Dependent:</strong> <?php echo htmlspecialchars($dependent['name'] ?? 'Not specified'); ?> 
                        (<?php echo ucwords(strtolower($dependent['relationship'] ?? '')); ?>)</li>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </ul>
            </div>
            <?php endif; ?>
            
            <?php if($policy['special_conditions']): ?>
            <div class="mb-3">
                <strong>Special Conditions:</strong>
                <p class="mt-2 mb-0 small"><?php echo nl2br(htmlspecialchars($policy['special_conditions'])); ?></p>
            </div>
            <?php endif; ?>
            
            <div class="text-center mt-4">
                <p class="mb-0 fw-bold text-success">This policy is valid and in force as of the date of issuance</p>
            </div>
        </div>

        <!-- Signatures -->
        <div class="signature-section">
            <div class="signature-block">
                <div class="signature-line">
                    <span style="font-family: cursive; font-size: 1.2rem; color: #2c5aa0;">Ultrasure Insurance</span>
                </div>
                <div><strong>Authorized Signature</strong></div>
                <div class="small">Company Representative</div>
            </div>
            
            <div class="text-center">
                <div class="qr-code">
                    QR CODE<br>
                    <small>Verify Online</small>
                </div>
                <div class="small mt-2">Scan to verify</div>
            </div>
            
            <div class="signature-block">
                <div class="signature-line">
                    <span style="font-family: cursive; font-size: 1.2rem; color: #2c5aa0;"><?php echo htmlspecialchars($policy['agent_name']); ?></span>
                </div>
                <div><strong>Agent Signature</strong></div>
                <div class="small">Code: <?php echo htmlspecialchars($policy['agent_code']); ?></div>
            </div>
        </div>

        <!-- Footer -->
        <div class="certificate-footer">
            <p class="mb-2">
                <strong>Certificate Generated:</strong> <?php echo formatDateTime(date('Y-m-d H:i:s')); ?>
            </p>
            <p class="mb-2">
                <strong>Generated by:</strong> <?php echo htmlspecialchars($_SESSION['full_name']); ?>
            </p>
            <p class="mb-0 small">
                This certificate is issued as evidence of insurance coverage. Please refer to the actual policy document for complete terms and conditions.
                For verification, visit our website or contact us directly.
            </p>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>