<?php
/**
 * Bengali Encoding Helper for CSV Files
 * This file contains functions to handle Bengali text encoding in CSV files
 */

class EncodingHelper {
    
    /**
     * Detect and convert CSV file encoding to UTF-8
     */
    public static function convertCsvToUtf8($filePath) {
        $content = file_get_contents($filePath);
        
        // Detect encoding
        $encoding = mb_detect_encoding($content, ['UTF-8', 'ISO-8859-1', 'Windows-1252', 'ASCII'], true);
        
        if ($encoding && $encoding !== 'UTF-8') {
            $content = mb_convert_encoding($content, 'UTF-8', $encoding);
            file_put_contents($filePath, $content);
        }
        
        return $encoding;
    }
    
    /**
     * Read CSV with proper Bengali encoding support
     */
    public static function readCsvWithBengaliSupport($filePath) {
        // First convert to UTF-8 if needed
        self::convertCsvToUtf8($filePath);
        
        $data = [];
        $handle = fopen($filePath, 'r');
        
        if ($handle !== FALSE) {
            while (($row = fgetcsv($handle, 0, ',', '"', '"')) !== FALSE) {
                // Clean and validate each field
                $cleanRow = array_map([self::class, 'cleanBengaliText'], $row);
                $data[] = $cleanRow;
            }
            fclose($handle);
        }
        
        return $data;
    }
    
    /**
     * Clean Bengali text and fix common encoding issues
     */
    public static function cleanBengaliText($text) {
        if (empty($text)) {
            return $text;
        }
        
        // Remove BOM if present
        $text = str_replace("\xEF\xBB\xBF", '', $text);
        
        // Trim whitespace
        $text = trim($text);
        
        // Fix common Bengali encoding issues
        $text = str_replace(['â€™', 'â€œ', 'â€'], ["'", '"', '–'], $text);
        
        // Ensure proper UTF-8 encoding
        if (!mb_check_encoding($text, 'UTF-8')) {
            $detected = mb_detect_encoding($text, ['UTF-8', 'ISO-8859-1', 'Windows-1252'], true);
            if ($detected) {
                $text = mb_convert_encoding($text, 'UTF-8', $detected);
            } else {
                $text = mb_convert_encoding($text, 'UTF-8', 'auto');
            }
        }
        
        return $text;
    }
    
    /**
     * Validate Bengali text
     */
    public static function validateBengaliText($text) {
        // Check if text contains Bengali characters
        return preg_match('/[\x{0980}-\x{09FF}]/u', $text);
    }
    
    /**
     * Create UTF-8 CSV template
     */
    public static function createUtf8CsvTemplate($headers, $sampleData, $filename) {
        $output = fopen($filename, 'w');
        
        // Add BOM for Excel compatibility
        fwrite($output, "\xEF\xBB\xBF");
        
        // Write headers
        fputcsv($output, $headers);
        
        // Write sample data
        foreach ($sampleData as $row) {
            fputcsv($output, $row);
        }
        
        fclose($output);
    }
    
    /**
     * Get file encoding information
     */
    public static function getFileEncodingInfo($filePath) {
        $content = file_get_contents($filePath);
        
        $encodings = ['UTF-8', 'ISO-8859-1', 'Windows-1252', 'ASCII'];
        $detected = mb_detect_encoding($content, $encodings, true);
        
        $hasBom = (substr($content, 0, 3) === "\xEF\xBB\xBF");
        $hasBengali = preg_match('/[\x{0980}-\x{09FF}]/u', $content);
        
        return [
            'detected_encoding' => $detected,
            'has_bom' => $hasBom,
            'has_bengali' => $hasBengali,
            'file_size' => filesize($filePath),
            'is_utf8' => ($detected === 'UTF-8')
        ];
    }
}

/**
 * CSV Processing Functions
 */

function processCsvWithBengaliSupport($filePath, $callback) {
    $results = [];
    $errors = [];
    
    try {
        // Get encoding info
        $encodingInfo = EncodingHelper::getFileEncodingInfo($filePath);
        
        // Read CSV data
        $csvData = EncodingHelper::readCsvWithBengaliSupport($filePath);
        
        if (empty($csvData)) {
            throw new Exception('CSV ফাইল খালি বা পড়া যাচ্ছে না');
        }
        
        // Skip header row
        $headers = array_shift($csvData);
        
        foreach ($csvData as $index => $row) {
            $rowNumber = $index + 2; // +2 because we skipped header and array is 0-indexed
            
            try {
                $result = $callback($row, $rowNumber, $headers);
                $results[] = $result;
            } catch (Exception $e) {
                $errors[] = [
                    'row' => $rowNumber,
                    'error' => $e->getMessage(),
                    'data' => $row
                ];
            }
        }
        
        return [
            'success' => true,
            'results' => $results,
            'errors' => $errors,
            'encoding_info' => $encodingInfo,
            'total_rows' => count($csvData),
            'successful_rows' => count($results),
            'failed_rows' => count($errors)
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage(),
            'results' => [],
            'errors' => []
        ];
    }
}

/**
 * Generate Bengali-friendly CSV templates
 */
function generateBengaliCsvTemplate($type) {
    $templates = [
        'students' => [
            'headers' => [
                'Student ID', 'First Name', 'Last Name', 'Email', 'Phone', 
                'Date of Birth', 'Gender', 'Address', 'Guardian Name', 
                'Guardian Phone', 'Guardian Email', 'Class ID', 'Roll Number', 'Admission Date'
            ],
            'sample_data' => [
                ['2024001', 'মোহাম্মদ রহিম', 'উদ্দিন', 'rahim@email.com', '01712345678', '2010-01-15', 'male', 'ঢাকা, বাংলাদেশ', 'মোহাম্মদ করিম', '01812345678', 'karim@email.com', '1', '01', '2024-01-01'],
                ['2024002', 'ফাতিমা আক্তার', 'খাতুন', 'fatima@email.com', '01712345679', '2010-02-20', 'female', 'চট্টগ্রাম, বাংলাদেশ', 'আব্দুল করিম', '01812345679', 'abdul@email.com', '1', '02', '2024-01-01']
            ]
        ],
        'teachers' => [
            'headers' => [
                'Teacher ID', 'First Name', 'Last Name', 'Email', 'Phone', 
                'Date of Birth', 'Gender', 'Address', 'Qualification', 
                'Experience', 'Subject Specialization', 'Joining Date', 'Salary', 'Designation'
            ],
            'sample_data' => [
                ['T001', 'মোহাম্মদ আহমদ', 'হাসান', 'ahmad@email.com', '01712345678', '1985-01-15', 'male', 'ঢাকা, বাংলাদেশ', 'ইংরেজিতে স্নাতকোত্তর', '৫ বছর', 'ইংরেজি', '2024-01-01', '25000', 'সহকারী শিক্ষক'],
                ['T002', 'ফাতিমা আক্তার', 'বেগম', 'fatima@email.com', '01712345679', '1988-02-20', 'female', 'চট্টগ্রাম, বাংলাদেশ', 'গণিতে স্নাতকোত্তর', '৩ বছর', 'গণিত', '2024-01-01', '23000', 'সহকারী শিক্ষক']
            ]
        ]
    ];
    
    return $templates[$type] ?? null;
}
?>