<?php

require_once(__DIR__ . '/../vendor/autoload.php');
require_once(__DIR__ . '/../config/db.php');

use PhpOffice\PhpSpreadsheet\IOFactory;

class ParserEngine {

    private $conn;

    public function __construct($conn){
        $this->conn = $conn;
    }

    /*
    ============================================
    EXTRAER TEXTO SEGÚN EXTENSIÓN
    ============================================
    */

    public function extractText($filePath){

        if(!file_exists($filePath)){
            return '';
        }

        $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));

        switch($extension){

            case 'txt':
                return $this->parseTXT($filePath);

            case 'csv':
                return $this->parseCSV($filePath);

            case 'pdf':
                return $this->parsePDF($filePath);

            case 'xlsx':
            case 'xls':
                return $this->parseExcel($filePath);

            default:
                return '';
        }
    }

    /*
    ============================================
    TXT
    ============================================
    */

    private function parseTXT($filePath){

        return file_get_contents($filePath);
    }

    /*
    ============================================
    CSV
    ============================================
    */

    private function parseCSV($filePath){

        $content = '';

        if(($handle = fopen($filePath, "r")) !== FALSE){

            while(($data = fgetcsv($handle, 10000, ",")) !== FALSE){

                $line = array_filter($data);

                if(!empty($line)){
                    $content .= implode(" | ", $line) . "\n";
                }
            }

            fclose($handle);
        }

        return $content;
    }

    /*
    ============================================
    PDF
    ============================================
    */

    private function parsePDF($filePath){

        $content = '';

        $escaped = escapeshellarg($filePath);

        $output = shell_exec("pdftotext $escaped -");

        if($output){
            $content = $output;
        }

        return $content;
    }

    /*
    ============================================
    EXCEL
    ============================================
    */

    private function parseExcel($filePath){

        $content = '';

        try{

            $spreadsheet = IOFactory::load($filePath);

            foreach($spreadsheet->getWorksheetIterator() as $worksheet){

                $rows = $worksheet->toArray(
    '',
    false,
    false,
    false
);

                foreach($rows as $row){

                    $cleanRow = [];

                    foreach($row as $cell){

                        if($cell === null){
                            continue;
                        }

                        $cell = trim((string)$cell);

                        if($cell === ''){
                            continue;
                        }

                        /*
                        IGNORAR ERRORES DE FORMULAS
                        */
                        if(
                            strpos($cell, '#') !== false ||
                            strpos($cell, 'Formula Error') !== false
                        ){
                            continue;
                        }

                        $cleanRow[] = $cell;
                    }

                    if(!empty($cleanRow)){

                        $line = implode(" | ", $cleanRow);

                        /*
                        EVITAR LÍNEAS REPETIDAS
                        */
                        if(strlen(trim($line)) > 3){
                            $content .= $line . "\n";
                        }
                    }
                }
            }

        }catch(Exception $e){

            return '';
        }

        return $content;
    }

    /*
    ============================================
    LIMPIAR TEXTO
    ============================================
    */

    public function cleanText($text){

        $text = strip_tags($text);

        $text = preg_replace('/\s+/', ' ', $text);

        $text = preg_replace('/[^\PC\s]/u', '', $text);

        return trim($text);
    }

    /*
    ============================================
    GUARDAR TEXTO IA
    ============================================
    */

    public function saveKnowledgeText($knowledgeId, $text){

        $text = $this->cleanText($text);

        $stmt = $this->conn->prepare("
            UPDATE knowledge_base
            SET extracted_text = ?
            WHERE id = ?
        ");

        $stmt->bind_param(
            "si",
            $text,
            $knowledgeId
        );

        return $stmt->execute();
    }

}

?>