<?php
/**
 * Document Processing Service
 * OCR and document data extraction
 * Kenyan Pension & Life Insurance Management System
 */

require_once __DIR__ . '/../includes/dbconn.php';

class DocumentProcessor {
    private $conn;
    private $ocrApiKey;
    private $ocrApiUrl = 'https://api.ocr.space/parse/imageurl';
    
    public function __construct($db_connection) {
        $this->conn = $db_connection;
        
        // Get OCR settings
        $settings = $this->conn->query("SELECT setting_value FROM system_settings 
                                       WHERE setting_key = 'ocr_api_key'")->fetch_assoc();
        $this->ocrApiKey = $settings['setting_value'] ?? '';
    }
    
    /**
     * Process uploaded document
     */
    public function processDocument($filePath, $documentType) {
        // Extract text using OCR
        $extractedText = $this->extractText($filePath);
        
        if (!$extractedText) {
            return [
                'success' => false,
                'message' => 'Failed to extract text from document'
            ];
        }
        
        // Parse document based on type
        switch ($documentType) {
            case 'NATIONAL_ID':
                return $this->parseNationalID($extractedText);
                
            case 'BIRTH_CERTIFICATE':
                return $this->parseBirthCertificate($extractedText);
                
            case 'CLAIM_DOCUMENT':
                return $this->parseClaimDocument($extractedText);
                
            case 'BANK_STATEMENT':
                return $this->parseBankStatement($extractedText);
                
            default:
                return [
                    'success' => true,
                    'raw_text' => $extractedText,
                    'message' => 'Document processed, manual review required'
                ];
        }
    }
    
    /**
     * Extract text from image using OCR
     */
    private function extractText($filePath) {
        if (empty($this->ocrApiKey)) {
            // Fallback: Use Tesseract if available
            if (function_exists('shell_exec') && shell_exec('which tesseract')) {
                return shell_exec("tesseract $filePath stdout");
            }
            return null;
        }
        
        // Use OCR.space API
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->ocrApiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, [
            'apikey' => $this->ocrApiKey,
            'url' => $filePath, // Or use file upload
            'language' => 'eng'
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        $result = json_decode($response, true);
        
        if (isset($result['ParsedResults'][0]['ParsedText'])) {
            return $result['ParsedResults'][0]['ParsedText'];
        }
        
        return null;
    }
    
    /**
     * Parse Kenyan National ID
     */
    private function parseNationalID($text) {
        $data = [
            'id_number' => $this->extractPattern($text, '/ID\s*NO[:\s]*([0-9]{8})/i'),
            'first_name' => $this->extractPattern($text, '/FIRST\s*NAME[:\s]*([A-Z\s]+)/i'),
            'last_name' => $this->extractPattern($text, '/SURNAME[:\s]*([A-Z\s]+)/i'),
            'date_of_birth' => $this->extractPattern($text, '/DOB[:\s]*([0-9]{2}\/[0-9]{2}\/[0-9]{4})/i'),
            'gender' => $this->extractPattern($text, '/SEX[:\s]*(MALE|FEMALE)/i'),
            'nationality' => $this->extractPattern($text, '/NATIONALITY[:\s]*([A-Z\s]+)/i')
        ];
        
        return [
            'success' => true,
            'document_type' => 'NATIONAL_ID',
            'extracted_data' => $data,
            'raw_text' => $text
        ];
    }
    
    /**
     * Parse birth certificate
     */
    private function parseBirthCertificate($text) {
        $data = [
            'child_name' => $this->extractPattern($text, '/NAME[:\s]*([A-Z\s]+)/i'),
            'date_of_birth' => $this->extractPattern($text, '/DATE\s*OF\s*BIRTH[:\s]*([0-9]{2}\/[0-9]{2}\/[0-9]{4})/i'),
            'place_of_birth' => $this->extractPattern($text, '/PLACE[:\s]*([A-Z\s,]+)/i'),
            'mother_name' => $this->extractPattern($text, '/MOTHER[:\s]*([A-Z\s]+)/i'),
            'father_name' => $this->extractPattern($text, '/FATHER[:\s]*([A-Z\s]+)/i')
        ];
        
        return [
            'success' => true,
            'document_type' => 'BIRTH_CERTIFICATE',
            'extracted_data' => $data,
            'raw_text' => $text
        ];
    }
    
    /**
     * Parse claim document
     */
    private function parseClaimDocument($text) {
        $data = [
            'claim_amount' => $this->extractPattern($text, '/AMOUNT[:\s]*KES?\s*([0-9,]+\.?[0-9]*)/i'),
            'claim_date' => $this->extractPattern($text, '/DATE[:\s]*([0-9]{2}\/[0-9]{2}\/[0-9]{4})/i'),
            'policy_number' => $this->extractPattern($text, '/POLICY[:\s]*NO[:\s]*([A-Z0-9-]+)/i'),
            'claim_type' => $this->extractPattern($text, '/TYPE[:\s]*(DEATH|MATURITY|DISABILITY)/i')
        ];
        
        return [
            'success' => true,
            'document_type' => 'CLAIM_DOCUMENT',
            'extracted_data' => $data,
            'raw_text' => $text
        ];
    }
    
    /**
     * Parse bank statement
     */
    private function parseBankStatement($text) {
        // Extract account number, transactions, etc.
        $data = [
            'account_number' => $this->extractPattern($text, '/ACCOUNT[:\s]*NO[:\s]*([0-9-]+)/i'),
            'bank_name' => $this->extractPattern($text, '/(KCB|EQUITY|COOPERATIVE|BARCLAYS|STANDARD\s*CHARTERED)/i'),
            'balance' => $this->extractPattern($text, '/BALANCE[:\s]*KES?\s*([0-9,]+\.?[0-9]*)/i')
        ];
        
        return [
            'success' => true,
            'document_type' => 'BANK_STATEMENT',
            'extracted_data' => $data,
            'raw_text' => $text
        ];
    }
    
    /**
     * Extract pattern from text
     */
    private function extractPattern($text, $pattern) {
        if (preg_match($pattern, $text, $matches)) {
            return trim($matches[1]);
        }
        return null;
    }
    
    /**
     * Save processed document
     */
    public function saveProcessedDocument($member_id, $documentType, $filePath, $extractedData) {
        $sql = "INSERT INTO processed_documents (
                   member_id, document_type, file_path,
                   extracted_data, processed_at, processed_by
               ) VALUES (?, ?, ?, ?, NOW(), 'SYSTEM')";
        
        $extractedJson = json_encode($extractedData);
        
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param("isss", $member_id, $documentType, $filePath, $extractedJson);
        
        if ($stmt->execute()) {
            return [
                'success' => true,
                'document_id' => $this->conn->insert_id
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Failed to save processed document'
        ];
    }
}
