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

// 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'];
$success_message = '';
$error_message = '';

// Get company ID from URL
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: list_insurers.php');
    exit();
}

$company_id = (int)$_GET['id'];

// Handle success message
if (isset($_GET['success'])) {
    if ($_GET['success'] == 'created') {
        $success_message = "Insurance company has been successfully created.";
    } elseif ($_GET['success'] == 'updated') {
        $success_message = "Insurance company has been successfully updated.";
    }
}

// Get company details
$sql = "SELECT * FROM insurance_companies WHERE company_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $company_id);
$stmt->execute();
$company = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$company) {
    header('Location: list_insurers.php');
    exit();
}

// Get company products
$products_sql = "SELECT 
    ip.*,
    pc.category_name,
    COUNT(p.policy_id) as active_policies,
    SUM(p.premium_amount) as total_premium
FROM insurance_products ip
LEFT JOIN product_categories pc ON ip.category_id = pc.category_id
LEFT JOIN policies p ON ip.product_id = p.product_id AND p.status = 'ACTIVE'
WHERE ip.company_id = ?
GROUP BY ip.product_id
ORDER BY ip.product_name";

$products_stmt = $conn->prepare($products_sql);
$products_stmt->bind_param("i", $company_id);
$products_stmt->execute();
$products_result = $products_stmt->get_result();

// Get company statistics
$stats_sql = "SELECT 
    COUNT(DISTINCT ip.product_id) as total_products,
    COUNT(DISTINCT p.policy_id) as total_policies,
    SUM(p.premium_amount) as total_premium_value,
    COUNT(DISTINCT p.customer_id) as total_customers,
    COUNT(DISTINCT CASE WHEN p.status = 'ACTIVE' THEN p.policy_id END) as active_policies
FROM insurance_products ip
LEFT JOIN policies p ON ip.product_id = p.product_id
WHERE ip.company_id = ?";

$stats_stmt = $conn->prepare($stats_sql);
$stats_stmt->bind_param("i", $company_id);
$stats_stmt->execute();
$stats = $stats_stmt->get_result()->fetch_assoc();
$stats_stmt->close();

// Parse commission structure
$commission_structure = [];
if ($company['commission_structure']) {
    $commission_structure = json_decode($company['commission_structure'], true) ?: [];
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $company['company_name'] . ' - Insurance Company Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .company-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.1);
            border-radius: 15px;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            border-radius: 15px;
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .integration-badge {
            font-size: 1rem;
            padding: 0.5rem 1rem;
        }
        
        .commission-badge {
            font-size: 0.875rem;
            padding: 0.375rem 0.75rem;
        }
        
        .product-card {
            border: 1px solid #e9ecef;
            border-radius: 10px;
            transition: all 0.3s ease;
        }
        
        .product-card:hover {
            border-color: #667eea;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Insurance Company 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_insurers.php">Insurance Companies</a></li>
                                        <li class="breadcrumb-item active"><?php echo htmlspecialchars($company['company_name']); ?></li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if ($success_message): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                <i class="ri-check-circle-line me-2"></i>
                                <?php echo htmlspecialchars($success_message); ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Company Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="company-header">
                                <div class="row align-items-center">
                                    <div class="col-md-8">
                                        <div class="d-flex align-items-center">
                                            <div class="avatar-lg me-4">
                                                <span class="avatar-title bg-white text-primary rounded-circle fs-2">
                                                    <?php echo strtoupper(substr($company['company_name'], 0, 2)); ?>
                                                </span>
                                            </div>
                                            <div>
                                                <h2 class="mb-2"><?php echo htmlspecialchars($company['company_name']); ?></h2>
                                                <div class="d-flex gap-3 mb-2">
                                                    <span class="badge bg-white text-dark">
                                                        Code: <?php echo htmlspecialchars($company['company_code']); ?>
                                                    </span>
                                                    <?php if ($company['short_name']): ?>
                                                    <span class="badge bg-white text-dark">
                                                        <?php echo htmlspecialchars($company['short_name']); ?>
                                                    </span>
                                                    <?php endif; ?>
                                                    <?php 
                                                    $integration_class = match($company['integration_type']) {
                                                        'API' => 'success',
                                                        'HYBRID' => 'warning',
                                                        'MANUAL' => 'info',
                                                        default => 'secondary'
                                                    };
                                                    ?>
                                                    <span class="badge bg-<?php echo $integration_class; ?> integration-badge">
                                                        <?php echo htmlspecialchars($company['integration_type']); ?> Integration
                                                    </span>
                                                </div>
                                                <div class="d-flex align-items-center gap-3">
                                                    <span class="badge bg-<?php echo $company['is_active'] ? 'success' : 'danger'; ?> integration-badge">
                                                        <?php echo $company['is_active'] ? 'Active' : 'Inactive'; ?>
                                                    </span>
                                                    <small class="opacity-75">
                                                        Added on <?php echo date('M j, Y', strtotime($company['created_at'])); ?>
                                                    </small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 text-md-end">
                                        <div class="d-flex flex-column flex-md-row gap-2">
                                            <a href="edit_insurer.php?id=<?php echo $company['company_id']; ?>" 
                                               class="btn btn-light">
                                                <i class="ri-edit-line me-1"></i>Edit Details
                                            </a>
                                            <div class="dropdown">
                                                <button class="btn btn-light dropdown-toggle" type="button" 
                                                        data-bs-toggle="dropdown">
                                                    <i class="ri-more-2-line"></i>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <li>
                                                        <a class="dropdown-item" href="add_product.php?company_id=<?php echo $company['company_id']; ?>">
                                                            <i class="ri-add-line me-2"></i>Add Product
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="insurer_products.php?company_id=<?php echo $company['company_id']; ?>">
                                                            <i class="ri-shield-check-line me-2"></i>View Products
                                                        </a>
                                                    </li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li>
                                                        <a class="dropdown-item" href="#" onclick="exportCompanyData()">
                                                            <i class="ri-download-line me-2"></i>Export Data
                                                        </a>
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="card stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-primary text-primary rounded-circle">
                                                    <i class="ri-shield-check-line fs-4"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="mb-1 text-primary"><?php echo number_format($stats['total_products']); ?></h4>
                                            <p class="mb-0 text-muted">Total Products</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-success text-success rounded-circle">
                                                    <i class="ri-file-text-line fs-4"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="mb-1 text-success"><?php echo number_format($stats['active_policies']); ?></h4>
                                            <p class="mb-0 text-muted">Active Policies</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-info text-info rounded-circle">
                                                    <i class="ri-money-dollar-circle-line fs-4"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="mb-1 text-info">KSH <?php echo number_format($stats['total_premium_value'], 2); ?></h4>
                                            <p class="mb-0 text-muted">Total Premium Value</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-warning text-warning rounded-circle">
                                                    <i class="ri-user-3-line fs-4"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="mb-1 text-warning"><?php echo number_format($stats['total_customers']); ?></h4>
                                            <p class="mb-0 text-muted">Total Customers</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Company Information -->
                        <div class="col-xl-8">
                            <!-- Contact Information -->
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-contacts-line me-2"></i>
                                        Contact Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Contact Person</label>
                                                <p class="mb-0 fw-medium"><?php echo htmlspecialchars($company['contact_person']); ?></p>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Email Address</label>
                                                <p class="mb-0">
                                                    <a href="mailto:<?php echo htmlspecialchars($company['email']); ?>" 
                                                       class="text-decoration-none">
                                                        <i class="ri-mail-line me-1"></i>
                                                        <?php echo htmlspecialchars($company['email']); ?>
                                                    </a>
                                                </p>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Phone Number</label>
                                                <p class="mb-0">
                                                    <a href="tel:<?php echo htmlspecialchars($company['phone']); ?>" 
                                                       class="text-decoration-none">
                                                        <i class="ri-phone-line me-1"></i>
                                                        <?php echo htmlspecialchars($company['phone']); ?>
                                                    </a>
                                                </p>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <?php if ($company['website']): ?>
                                            <div class="mb-3">
                                                <label class="form-label text-muted">Website</label>
                                                <p class="mb-0">
                                                    <a href="<?php echo htmlspecialchars($company['website']); ?>" 
                                                       target="_blank" class="text-decoration-none">
                                                        <i class="ri-global-line me-1"></i>
                                                        <?php echo htmlspecialchars($company['website']); ?>
                                                        <i class="ri-external-link-line ms-1"></i>
                                                    </a>
                                                </p>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($company['license_number']): ?>
                                            <div class="mb-3">
                                                <label class="form-label text-muted">License Number</label>
                                                <p class="mb-0 fw-medium"><?php echo htmlspecialchars($company['license_number']); ?></p>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if ($company['api_endpoint']): ?>
                                            <div class="mb-3">
                                                <label class="form-label text-muted">API Endpoint</label>
                                                <p class="mb-0">
                                                    <code><?php echo htmlspecialchars($company['api_endpoint']); ?></code>
                                                </p>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <?php if ($company['address']): ?>
                                    <div class="mt-3">
                                        <label class="form-label text-muted">Address</label>
                                        <p class="mb-0"><?php echo nl2br(htmlspecialchars($company['address'])); ?></p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Commission Structure -->
                            <?php if (!empty($commission_structure)): ?>
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-percent-line me-2"></i>
                                        Commission Structure
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <?php foreach ($commission_structure as $type => $rate): ?>
                                        <div class="col-md-4 mb-3">
                                            <div class="d-flex justify-content-between align-items-center p-3 bg-light rounded">
                                                <span class="fw-medium"><?php echo ucfirst(strtolower(str_replace('_', ' ', $type))); ?></span>
                                                <span class="badge bg-primary commission-badge"><?php echo $rate; ?>%</span>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Payment Terms -->
                            <?php if ($company['payment_terms']): ?>
                            <div class="card info-card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-money-dollar-circle-line me-2"></i>
                                        Payment Terms
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($company['payment_terms'])); ?></p>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>

                        <!-- Products List -->
                        <div class="col-xl-4">
                            <div class="card info-card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">
                                        <i class="ri-shield-check-line me-2"></i>
                                        Insurance Products
                                    </h5>
                                    <a href="add_product.php?company_id=<?php echo $company['company_id']; ?>" 
                                       class="btn btn-sm btn-primary">
                                        <i class="ri-add-line me-1"></i>Add Product
                                    </a>
                                </div>
                                <div class="card-body">
                                    <?php if ($products_result->num_rows > 0): ?>
                                    <div class="list-group list-group-flush">
                                        <?php while($product = $products_result->fetch_assoc()): ?>
                                        <div class="list-group-item product-card p-3 mb-2">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-1">
                                                        <a href="products/view_product.php?id=<?php echo $product['product_id']; ?>" 
                                                           class="text-decoration-none">
                                                            <?php echo htmlspecialchars($product['product_name']); ?>
                                                        </a>
                                                    </h6>
                                                    <p class="mb-2 text-muted small">
                                                        <?php echo htmlspecialchars($product['category_name']); ?> | 
                                                        <?php echo ucfirst(strtolower($product['coverage_type'])); ?>
                                                    </p>
                                                    <div class="d-flex gap-2">
                                                        <span class="badge bg-soft-info text-info">
                                                            <?php echo $product['active_policies']; ?> policies
                                                        </span>
                                                        <?php if ($product['total_premium'] > 0): ?>
                                                        <span class="badge bg-soft-success text-success">
                                                            KSH <?php echo number_format($product['total_premium'], 0); ?>
                                                        </span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                <span class="badge bg-<?php echo $product['is_active'] ? 'success' : 'secondary'; ?>">
                                                    <?php echo $product['is_active'] ? 'Active' : 'Inactive'; ?>
                                                </span>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    </div>
                                    
                                    <?php if ($products_result->num_rows >= 5): ?>
                                    <div class="text-center mt-3">
                                        <a href="insurer_products.php?company_id=<?php echo $company['company_id']; ?>" 
                                           class="btn btn-outline-primary btn-sm">
                                            View All Products
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php else: ?>
                                    <div class="text-center py-4">
                                        <div class="avatar-sm mx-auto mb-3">
                                            <span class="avatar-title bg-soft-primary text-primary rounded-circle">
                                                <i class="ri-shield-check-line"></i>
                                            </span>
                                        </div>
                                        <p class="text-muted mb-3">No products available</p>
                                        <a href="add_product.php?company_id=<?php echo $company['company_id']; ?>" 
                                           class="btn btn-sm btn-primary">
                                            <i class="ri-add-line me-1"></i>Add First Product
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </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 exportCompanyData() {
            // Create company data export
            const companyData = {
                name: "<?php echo htmlspecialchars($company['company_name']); ?>",
                code: "<?php echo htmlspecialchars($company['company_code']); ?>",
                contact: "<?php echo htmlspecialchars($company['contact_person']); ?>",
                email: "<?php echo htmlspecialchars($company['email']); ?>",
                phone: "<?php echo htmlspecialchars($company['phone']); ?>",
                integration: "<?php echo htmlspecialchars($company['integration_type']); ?>",
                status: "<?php echo $company['is_active'] ? 'Active' : 'Inactive'; ?>",
                total_products: "<?php echo $stats['total_products']; ?>",
                active_policies: "<?php echo $stats['active_policies']; ?>",
                total_premium: "<?php echo $stats['total_premium_value']; ?>",
                total_customers: "<?php echo $stats['total_customers']; ?>"
            };
            
            // Convert to CSV
            const csvHeaders = Object.keys(companyData).join(',');
            const csvData = Object.values(companyData).map(value => `"${value}"`).join(',');
            const csvContent = csvHeaders + '\n' + csvData;
            
            // Download
            const blob = new Blob([csvContent], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'company_data_<?php echo $company['company_code']; ?>_' + new Date().toISOString().slice(0, 10) + '.csv';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }
    </script>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>