<?php
/**
 * Insurance Functions Helper File
 * Common functions for insurance company management
 */

/**
 * Log activity to the database
 */
function logActivity($conn, $user_id, $action, $module, $record_id, $old_values = null, $new_values = null) {
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $session_id = session_id();
    
    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, old_values, new_values, ip_address, user_agent, session_id) 
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $log_stmt = $conn->prepare($log_sql);
    $record_type = strtoupper($module);
    $old_values_json = $old_values ? json_encode($old_values) : null;
    $new_values_json = $new_values ? json_encode($new_values) : null;
    
    $log_stmt->bind_param("ississssss", 
        $user_id, $action, $module, $record_id, $record_type, 
        $old_values_json, $new_values_json, $ip_address, $user_agent, $session_id
    );
    
    return $log_stmt->execute();
}

/**
 * Check if user has permission
 */
function hasPermission($permission_name) {
    // For now, return true for all permissions
    // This should be integrated with your permission system
    return true;
}

/**
 * Generate unique company code
 */
function generateCompanyCode($company_name, $conn) {
    // Extract initials from company name
    $words = explode(' ', $company_name);
    $code = '';
    
    foreach ($words as $word) {
        $clean_word = preg_replace('/[^a-zA-Z]/', '', $word);
        if (!empty($clean_word)) {
            $code .= strtoupper(substr($clean_word, 0, 1));
        }
    }
    
    // If code is too short, use first 3 characters of first word
    if (strlen($code) < 3) {
        $first_word = preg_replace('/[^a-zA-Z]/', '', $words[0]);
        $code = strtoupper(substr($first_word, 0, 3));
    }
    
    // Ensure code is unique
    $original_code = $code;
    $counter = 1;
    
    while (true) {
        $check_sql = "SELECT company_id FROM insurance_companies WHERE company_code = ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param("s", $code);
        $check_stmt->execute();
        
        if ($check_stmt->get_result()->num_rows == 0) {
            break;
        }
        
        $code = $original_code . $counter;
        $counter++;
    }
    
    return $code;
}

/**
 * Get company statistics
 */
function getCompanyStats($company_id, $conn) {
    $stats_sql = "SELECT 
        COUNT(DISTINCT ip.product_id) as total_products,
        COUNT(DISTINCT p.policy_id) as total_policies,
        SUM(CASE WHEN p.status = 'ACTIVE' THEN p.premium_amount ELSE 0 END) as active_premium,
        SUM(p.premium_amount) as total_premium,
        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();
    
    return $stats_stmt->get_result()->fetch_assoc();
}

/**
 * Validate email address
 */
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

/**
 * Validate phone number (basic validation for Kenyan numbers)
 */
function validatePhone($phone) {
    // Remove all non-numeric characters
    $clean_phone = preg_replace('/[^0-9+]/', '', $phone);
    
    // Check if it's a valid Kenyan number
    if (preg_match('/^(\+254|254|0)[17]\d{8}$/', $clean_phone)) {
        return true;
    }
    
    // Check for landline
    if (preg_match('/^(\+254|254|0)[2-6]\d{7}$/', $clean_phone)) {
        return true;
    }
    
    return false;
}

/**
 * Format phone number to Kenyan standard
 */
function formatPhone($phone) {
    $clean_phone = preg_replace('/[^0-9+]/', '', $phone);
    
    // Convert to +254 format
    if (preg_match('/^0([17]\d{8})$/', $clean_phone, $matches)) {
        return '+254' . $matches[1];
    }
    
    if (preg_match('/^254([17]\d{8})$/', $clean_phone, $matches)) {
        return '+254' . $matches[1];
    }
    
    if (preg_match('/^\+254([17]\d{8})$/', $clean_phone)) {
        return $clean_phone;
    }
    
    return $phone; // Return original if no match
}

/**
 * Get integration type badge class
 */
function getIntegrationBadgeClass($integration_type) {
    switch (strtoupper($integration_type)) {
        case 'API':
            return 'success';
        case 'HYBRID':
            return 'warning';
        case 'MANUAL':
            return 'secondary';
        default:
            return 'secondary';
    }
}

/**
 * Format currency for display
 */
function formatCurrency($amount, $currency = 'KSH') {
    return $currency . ' ' . number_format($amount, 2);
}

/**
 * Sanitize input data
 */
function sanitizeInput($data) {
    return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}

/**
 * Check if company can be deleted
 */
function canDeleteCompany($company_id, $conn) {
    // Check for products
    $products_sql = "SELECT COUNT(*) as count FROM insurance_products WHERE company_id = ?";
    $products_stmt = $conn->prepare($products_sql);
    $products_stmt->bind_param("i", $company_id);
    $products_stmt->execute();
    $products_count = $products_stmt->get_result()->fetch_assoc()['count'];
    
    if ($products_count > 0) {
        return [
            'can_delete' => false,
            'reason' => "Company has {$products_count} products associated with it."
        ];
    }
    
    // Check for policies
    $policies_sql = "SELECT COUNT(*) as count FROM policies p 
                    JOIN insurance_products ip ON p.product_id = ip.product_id 
                    WHERE ip.company_id = ?";
    $policies_stmt = $conn->prepare($policies_sql);
    $policies_stmt->bind_param("i", $company_id);
    $policies_stmt->execute();
    $policies_count = $policies_stmt->get_result()->fetch_assoc()['count'];
    
    if ($policies_count > 0) {
        return [
            'can_delete' => false,
            'reason' => "Company has {$policies_count} policies associated with it."
        ];
    }
    
    return ['can_delete' => true, 'reason' => ''];
}

/**
 * Get company dropdown options
 */
function getCompanyOptions($conn, $selected_id = null) {
    $sql = "SELECT company_id, company_name, company_code FROM insurance_companies 
            WHERE is_active = 1 ORDER BY company_name";
    $result = $conn->query($sql);
    
    $options = '';
    while ($row = $result->fetch_assoc()) {
        $selected = ($selected_id == $row['company_id']) ? 'selected' : '';
        $options .= "<option value='{$row['company_id']}' {$selected}>" . 
                   htmlspecialchars($row['company_name']) . "</option>";
    }
    
    return $options;
}

/**
 * Validate company data
 */
function validateCompanyData($data) {
    $errors = [];
    
    // Required fields
    $required_fields = ['company_name', 'company_code', 'contact_person', 'email', 'phone'];
    foreach ($required_fields as $field) {
        if (empty($data[$field])) {
            $errors[] = ucfirst(str_replace('_', ' ', $field)) . " is required.";
        }
    }
    
    // Email validation
    if (!empty($data['email']) && !validateEmail($data['email'])) {
        $errors[] = "Please provide a valid email address.";
    }
    
    // Phone validation
    if (!empty($data['phone']) && !validatePhone($data['phone'])) {
        $errors[] = "Please provide a valid phone number.";
    }
    
    // URL validation
    if (!empty($data['website']) && !filter_var($data['website'], FILTER_VALIDATE_URL)) {
        $errors[] = "Please provide a valid website URL.";
    }
    
    if (!empty($data['api_endpoint']) && !filter_var($data['api_endpoint'], FILTER_VALIDATE_URL)) {
        $errors[] = "Please provide a valid API endpoint URL.";
    }
    
    return $errors;
}

/**
 * Generate company report data
 */
function generateCompanyReport($company_id, $conn) {
    $company_sql = "SELECT * FROM insurance_companies WHERE company_id = ?";
    $company_stmt = $conn->prepare($company_sql);
    $company_stmt->bind_param("i", $company_id);
    $company_stmt->execute();
    $company = $company_stmt->get_result()->fetch_assoc();
    
    if (!$company) {
        return null;
    }
    
    $stats = getCompanyStats($company_id, $conn);
    
    return [
        'company' => $company,
        'stats' => $stats,
        'generated_at' => date('Y-m-d H:i:s')
    ];
}

/**
 * Get recent activity for company
 */
function getCompanyActivity($company_id, $conn, $limit = 10) {
    $activity_sql = "SELECT 
        al.*,
        u.full_name as user_name
    FROM activity_log al
    LEFT JOIN users u ON al.user_id = u.user_id
    WHERE al.module = 'INSURER' AND al.record_id = ?
    ORDER BY al.logged_at DESC
    LIMIT ?";
    
    $activity_stmt = $conn->prepare($activity_sql);
    $activity_stmt->bind_param("ii", $company_id, $limit);
    $activity_stmt->execute();
    
    return $activity_stmt->get_result();
}

/**
 * Check for duplicate company
 */
function isDuplicateCompany($company_name, $company_code, $conn, $exclude_id = null) {
    $sql = "SELECT company_id FROM insurance_companies 
            WHERE (company_name = ? OR company_code = ?)";
    $params = [$company_name, $company_code];
    $types = "ss";
    
    if ($exclude_id) {
        $sql .= " AND company_id != ?";
        $params[] = $exclude_id;
        $types .= "i";
    }
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    
    return $stmt->get_result()->num_rows > 0;
}

/**
 * Update company status
 */
function updateCompanyStatus($company_id, $status, $user_id, $conn) {
    $update_sql = "UPDATE insurance_companies SET is_active = ?, updated_at = NOW() WHERE company_id = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param("ii", $status, $company_id);
    
    if ($update_stmt->execute()) {
        // Log the activity
        logActivity($conn, $user_id, 'STATUS_UPDATE', 'INSURER', $company_id, 
                   null, ['status' => $status ? 'activated' : 'deactivated']);
        return true;
    }
    
    return false;
}
?>