<?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 = '';

// Handle success message from add/edit
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.";
    } elseif ($_GET['success'] == 'deleted') {
        $success_message = "Insurance company has been successfully deleted.";
    }
}

// Handle delete action
if (isset($_POST['delete_company']) && isset($_POST['company_id'])) {
    try {
        $company_id = (int)$_POST['company_id'];
        
        // Check if company has any products
        $check_products_sql = "SELECT COUNT(*) as product_count FROM insurance_products WHERE company_id = ?";
        $check_stmt = $conn->prepare($check_products_sql);
        $check_stmt->bind_param("i", $company_id);
        $check_stmt->execute();
        $product_count = $check_stmt->get_result()->fetch_assoc()['product_count'];
        $check_stmt->close();
        
        if ($product_count > 0) {
            throw new Exception("Cannot delete company. There are {$product_count} products associated with this company.");
        }
        
        // Delete the company
        $delete_sql = "DELETE FROM insurance_companies WHERE company_id = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        $delete_stmt->bind_param("i", $company_id);
        
        if ($delete_stmt->execute()) {
            // Log activity
            $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, old_values, ip_address) 
                       VALUES (?, 'DELETE', 'INSURER', ?, 'COMPANY', ?, ?)";
            $log_stmt = $conn->prepare($log_sql);
            $activity_data = json_encode(['company_id' => $company_id, 'deleted_by' => $user_id]);
            $ip_address = $_SERVER['REMOTE_ADDR'];
            $log_stmt->bind_param("iiss", $user_id, $company_id, $activity_data, $ip_address);
            $log_stmt->execute();
            $log_stmt->close();
            
            header("Location: list_insurers.php?success=deleted");
            exit();
        } else {
            throw new Exception("Failed to delete company. Please try again.");
        }
        
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

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

// Search functionality
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';

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

if (!empty($search)) {
    $where_conditions[] = "(company_name LIKE ? OR company_code LIKE ? OR contact_person LIKE ?)";
    $search_param = "%{$search}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $param_types .= 'sss';
}

if ($status_filter !== '') {
    $where_conditions[] = "is_active = ?";
    $params[] = (int)$status_filter;
    $param_types .= 'i';
}

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

// Get total count for pagination
$count_sql = "SELECT COUNT(*) as total FROM insurance_companies {$where_clause}";
$count_stmt = $conn->prepare($count_sql);
if (!empty($params)) {
    $count_stmt->bind_param($param_types, ...$params);
}
$count_stmt->execute();
$total_records = $count_stmt->get_result()->fetch_assoc()['total'];
$count_stmt->close();

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

// Get dashboard statistics
$stats_sql = "SELECT 
    COUNT(*) as total_companies,
    SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_companies,
    SUM(CASE WHEN integration_type IN ('API', 'HYBRID') AND is_active = 1 THEN 1 ELSE 0 END) as api_integrated,
    (SELECT COUNT(*) FROM insurance_products) as total_products
FROM insurance_companies";

$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

// Get insurance companies data
$sql = "SELECT 
    company_id,
    company_code,
    company_name,
    short_name,
    contact_person,
    email,
    phone,
    integration_type,
    is_active,
    created_at,
    (SELECT COUNT(*) FROM insurance_products WHERE company_id = ic.company_id) as product_count
FROM insurance_companies ic 
{$where_clause}
ORDER BY company_name ASC 
LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);
$params[] = $records_per_page;
$params[] = $offset;
$param_types .= 'ii';

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

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Insurance Companies - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <style>
        .company-card {
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-radius: 15px;
            transition: all 0.3s ease;
        }
        
        .company-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .integration-badge {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
        }
        
        .search-card {
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            border-radius: 15px;
        }
    </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 Companies</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 active">Insurance Companies</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; ?>

                    <?php if ($error_message): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="ri-error-warning-line me-2"></i>
                                <?php echo htmlspecialchars($error_message); ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics Row -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <i class="ri-building-line fs-2"></i>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="mb-1"><?php echo number_format($stats['total_companies']); ?></h4>
                                            <p class="mb-0 opacity-75">Total Companies</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <i class="ri-checkbox-circle-line fs-2"></i>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="mb-1"><?php echo number_format($stats['active_companies']); ?></h4>
                                            <p class="mb-0 opacity-75">Active Companies</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <i class="ri-plug-line fs-2"></i>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="mb-1"><?php echo number_format($stats['api_integrated']); ?></h4>
                                            <p class="mb-0 opacity-75">API Integrated</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card stats-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <i class="ri-shield-check-line fs-2"></i>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <h4 class="mb-1"><?php echo number_format($stats['total_products']); ?></h4>
                                            <p class="mb-0 opacity-75">Total Products</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Search and Filter Card -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card search-card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-4">
                                            <div class="form-floating">
                                                <input type="text" class="form-control" id="search" name="search" 
                                                       placeholder="Search companies..." 
                                                       value="<?php echo htmlspecialchars($search); ?>">
                                                <label for="search">Search Companies</label>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-3">
                                            <div class="form-floating">
                                                <select class="form-select" id="status" name="status">
                                                    <option value="">All Status</option>
                                                    <option value="1" <?php echo $status_filter === '1' ? 'selected' : ''; ?>>Active</option>
                                                    <option value="0" <?php echo $status_filter === '0' ? 'selected' : ''; ?>>Inactive</option>
                                                </select>
                                                <label for="status">Status Filter</label>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-3">
                                            <button type="submit" class="btn btn-primary w-100 h-100">
                                                <i class="ri-search-line me-2"></i>Search
                                            </button>
                                        </div>
                                        
                                        <div class="col-md-2">
                                            <a href="add_insurer.php" class="btn btn-success w-100 h-100">
                                                <i class="ri-add-line me-2"></i>Add Company
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Companies Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card company-card">
                                <div class="card-header border-0 pb-0">
                                    <div class="d-flex align-items-center justify-content-between">
                                        <h5 class="mb-0">
                                            <i class="ri-building-line me-2"></i>
                                            Insurance Companies (<?php echo $total_records; ?>)
                                        </h5>
                                        <div class="d-flex gap-2">
                                            <button class="btn btn-outline-primary btn-sm" onclick="exportData()">
                                                <i class="ri-download-line me-1"></i>Export
                                            </button>
                                            <button class="btn btn-outline-info btn-sm" onclick="location.reload()">
                                                <i class="ri-refresh-line me-1"></i>Refresh
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="card-body">
                                    <?php if ($result->num_rows > 0): ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover align-middle" id="companiesTable">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Company Details</th>
                                                    <th>Contact Information</th>
                                                    <th>Integration</th>
                                                    <th>Products</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while($row = $result->fetch_assoc()): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="avatar-sm me-3">
                                                                <span class="avatar-title bg-soft-primary text-primary rounded-circle">
                                                                    <?php echo strtoupper(substr($row['company_name'], 0, 2)); ?>
                                                                </span>
                                                            </div>
                                                            <div>
                                                                <h6 class="mb-1">
                                                                    <a href="view_insurer.php?id=<?php echo $row['company_id']; ?>" 
                                                                       class="text-dark text-decoration-none">
                                                                        <?php echo htmlspecialchars($row['company_name']); ?>
                                                                    </a>
                                                                </h6>
                                                                <div class="d-flex gap-2">
                                                                    <span class="badge bg-soft-info text-info">
                                                                        <?php echo htmlspecialchars($row['company_code']); ?>
                                                                    </span>
                                                                    <?php if ($row['short_name']): ?>
                                                                    <small class="text-muted">
                                                                        (<?php echo htmlspecialchars($row['short_name']); ?>)
                                                                    </small>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    
                                                    <td>
                                                        <div>
                                                            <div class="fw-medium"><?php echo htmlspecialchars($row['contact_person']); ?></div>
                                                            <div class="text-muted small">
                                                                <i class="ri-mail-line me-1"></i>
                                                                <?php echo htmlspecialchars($row['email']); ?>
                                                            </div>
                                                            <div class="text-muted small">
                                                                <i class="ri-phone-line me-1"></i>
                                                                <?php echo htmlspecialchars($row['phone']); ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    
                                                    <td>
                                                        <?php 
                                                        $integration_class = match($row['integration_type']) {
                                                            'API' => 'success',
                                                            'HYBRID' => 'warning',
                                                            'MANUAL' => 'secondary',
                                                            default => 'secondary'
                                                        };
                                                        ?>
                                                        <span class="badge bg-<?php echo $integration_class; ?> integration-badge">
                                                            <?php echo htmlspecialchars($row['integration_type']); ?>
                                                        </span>
                                                    </td>
                                                    
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <i class="ri-shield-check-line text-primary me-2"></i>
                                                            <span class="fw-medium"><?php echo $row['product_count']; ?></span>
                                                            <small class="text-muted ms-1">products</small>
                                                        </div>
                                                    </td>
                                                    
                                                    <td>
                                                        <span class="badge bg-<?php echo $row['is_active'] ? 'success' : 'danger'; ?>">
                                                            <?php echo $row['is_active'] ? 'Active' : 'Inactive'; ?>
                                                        </span>
                                                    </td>
                                                    
                                                    <td>
                                                        <div class="dropdown">
                                                            <button class="btn btn-soft-secondary btn-sm dropdown-toggle" 
                                                                    type="button" data-bs-toggle="dropdown">
                                                                <i class="ri-more-2-fill"></i>
                                                            </button>
                                                            <ul class="dropdown-menu">
                                                                <li>
                                                                    <a class="dropdown-item" 
                                                                       href="view_insurer.php?id=<?php echo $row['company_id']; ?>">
                                                                        <i class="ri-eye-line me-2"></i>View Details
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a class="dropdown-item" 
                                                                       href="edit_insurer.php?id=<?php echo $row['company_id']; ?>">
                                                                        <i class="ri-edit-line me-2"></i>Edit
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a class="dropdown-item" 
                                                                       href="insurer_products.php?company_id=<?php echo $row['company_id']; ?>">
                                                                        <i class="ri-shield-check-line me-2"></i>View Products
                                                                    </a>
                                                                </li>
                                                                <li><hr class="dropdown-divider"></li>
                                                                <li>
                                                                    <button class="dropdown-item text-danger" 
                                                                            onclick="confirmDelete(<?php echo $row['company_id']; ?>, '<?php echo htmlspecialchars($row['company_name']); ?>')">
                                                                        <i class="ri-delete-bin-line me-2"></i>Delete
                                                                    </button>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>

                                    <!-- Pagination -->
                                    <?php if ($total_pages > 1): ?>
                                    <nav aria-label="Companies pagination" class="mt-4">
                                        <ul class="pagination pagination-sm justify-content-center">
                                            <?php if ($page > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status_filter; ?>">
                                                    <i class="ri-arrow-left-line"></i>
                                                </a>
                                            </li>
                                            <?php endif; ?>
                                            
                                            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                            <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status_filter; ?>">
                                                    <?php echo $i; ?>
                                                </a>
                                            </li>
                                            <?php endfor; ?>
                                            
                                            <?php if ($page < $total_pages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status_filter; ?>">
                                                    <i class="ri-arrow-right-line"></i>
                                                </a>
                                            </li>
                                            <?php endif; ?>
                                        </ul>
                                    </nav>
                                    <?php endif; ?>
                                    
                                    <?php else: ?>
                                    <div class="text-center py-5">
                                        <div class="avatar-lg mx-auto mb-4">
                                            <div class="avatar-title bg-soft-primary text-primary rounded-circle">
                                                <i class="ri-building-line fs-1"></i>
                                            </div>
                                        </div>
                                        <h5>No insurance companies found</h5>
                                        <p class="text-muted">
                                            <?php if (!empty($search) || $status_filter !== ''): ?>
                                                No companies match your search criteria. Try adjusting your filters.
                                            <?php else: ?>
                                                Start by adding your first insurance company partner.
                                            <?php endif; ?>
                                        </p>
                                        <a href="add_insurer.php" class="btn btn-primary">
                                            <i class="ri-add-line me-2"></i>Add Insurance Company
                                        </a>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">Confirm Delete</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete <strong id="companyNameToDelete"></strong>?</p>
                    <p class="text-muted small">This action cannot be undone. All related data will be permanently removed.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <form method="POST" style="display: inline;">
                        <input type="hidden" name="company_id" id="companyIdToDelete">
                        <button type="submit" name="delete_company" class="btn btn-danger">
                            <i class="ri-delete-bin-line me-1"></i>Delete Company
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTable for better sorting and searching
            $('#companiesTable').DataTable({
                "paging": false,
                "searching": false,
                "info": false,
                "ordering": true,
                "order": [[0, 'asc']],
                "columnDefs": [
                    { "orderable": false, "targets": [5] } // Disable sorting on Actions column
                ]
            });
        });
        
        function confirmDelete(companyId, companyName) {
            $('#companyIdToDelete').val(companyId);
            $('#companyNameToDelete').text(companyName);
            $('#deleteModal').modal('show');
        }
        
        function exportData() {
            // Simple export functionality
            let table = document.getElementById('companiesTable');
            let csv = [];
            
            // Headers
            let headers = [];
            table.querySelectorAll('thead th').forEach(function(th, index) {
                if (index < 5) { // Exclude Actions column
                    headers.push('"' + th.textContent.trim() + '"');
                }
            });
            csv.push(headers.join(','));
            
            // Data rows
            table.querySelectorAll('tbody tr').forEach(function(tr) {
                let row = [];
                tr.querySelectorAll('td').forEach(function(td, index) {
                    if (index < 5) { // Exclude Actions column
                        row.push('"' + td.textContent.trim().replace(/"/g, '""') + '"');
                    }
                });
                csv.push(row.join(','));
            });
            
            // Download CSV
            let csvContent = csv.join('\n');
            let blob = new Blob([csvContent], { type: 'text/csv' });
            let url = window.URL.createObjectURL(blob);
            let a = document.createElement('a');
            a.href = url;
            a.download = 'insurance_companies_' + 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>