<?php 

trait CurriculoIACore {

    public static function start($instruction, $text) {

        $response = AICore::chat(
            [
                'model' => 'gpt-4o',
                'max_tokens' => 5000,
                'temperature' => 1,
                'response_format' => [
                    'type' => 'json_object'
                ]
            ],
            $instruction,
            $text
        );

        return $response;
    }

    public static function saveCurriculoData($json, $lead_id) {

        if (isset($json['professionalHistoric']))
            self::insertProfessionalExperiences($json['professionalHistoric'], $lead_id);

        if (isset($json['educationHistoric']))
            self::insertEducationHistoric($json['educationHistoric'], $lead_id);

    }

    
    protected static function insertEducationHistoric($educations, $lead_id)
    {

        $sql = "INSERT INTO education_experience(lead_id, education_level, institution_name, course_name, date_start, date_end) 
            VALUES (:lead_id, '', :institution_name, :course_name, :date_start, :date_end)";

        foreach ($educations as $education) {            

            if (isset($education['startDate']) && !empty($education['startDate'])) {

                if(self::selectEducationByDate($lead_id, $education['startDate'])) {
                    continue;
                }

                if (preg_match('/^\d{4}-\d{2}$/', $education['startDate'])) {
                    list($start_date_year, $start_date_month) = explode('-', $education['startDate']);
                    $start_date = "{$start_date_year}-{$start_date_month}-01";
                } else {
                    $start_date =  "";
                }
            }

            if (isset($education['endDate']) && !empty($education['endDate'])) {
                if (preg_match('/^\d{4}-\d{2}$/', $education['endDate'])) {
                    list($end_date_year, $end_date_month) =  explode('-', $education['endDate']);
                    $end_date = "{$end_date_year}-{$end_date_month}-01";
                } else {
                    $end_date = "";
                }
            }

            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([
                ':lead_id' => $lead_id,
                ':institution_name' => $education['institution'],
                ':course_name' => $education['name'],
                ':date_start' => $start_date ?? null,
                ':date_end' => $end_date ?? null,
            ]);
        }
    }

    protected static function insertProfessionalExperiences($experiences, $lead_id)
    {

        $sql = "INSERT INTO professional_experiences(lead_id, organization, sinonimo, description, init_date, final_date) 
                    VALUES (:lead_id, :organization, :sinonimo, :description, :init_date, :final_date)";

        foreach ($experiences as $job) {

            if (isset($job['startDate']) && !empty($job['startDate'])) {

                if(self::selectProfessionalExperienceByDate($lead_id, $job['startDate'])) {
                    continue;
                }

                if (preg_match('/^\d{4}-\d{2}$/', $job['startDate'])) {
                    list($start_date_year, $start_date_month) = explode('-', $job['startDate']);
                    $start_date = "{$start_date_year}-{$start_date_month}-01";
                } else {
                    $start_date = "";
                }
            }

            if (isset($job['endDate']) && !empty($job['endDate'])) {
                if (preg_match('/^\d{4}-\d{2}$/', $job['endDate'])) {
                    list($end_date_year, $end_date_month) =  explode('-', $job['endDate']);
                    $end_date = "{$end_date_year}-{$end_date_month}-01";
                } else {
                    $end_date = "";
                }
            }

            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([
                ':lead_id' => $lead_id,
                ':sinonimo' => $job['name'],
                ':organization' => $job['company'],
                ':description' => $job['description'],
                ':init_date' => $start_date ?? null,
                ':final_date' => $end_date ?? null,
            ]);
        }
        
    }

    private static function selectProfessionalExperienceByDate($lead_id, $start_date) {
        // garantir formato YYYY-MM (aceita YYYY-MM ou YYYY-MM-DD)
        $start_date = substr($start_date, 0, 7);

        $sql = "SELECT * FROM professional_experiences 
            WHERE lead_id = :lead_id AND DATE_FORMAT(init_date, '%Y-%m') = :start_date";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':lead_id' => $lead_id,
            ':start_date' => $start_date
        ]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    private static function selectEducationByDate($lead_id, $start_date) {
        // garantir formato YYYY-MM (aceita YYYY-MM ou YYYY-MM-DD)
        $start_date = substr($start_date, 0, 7);

        $sql = "SELECT * FROM education_experience 
            WHERE lead_id = :lead_id AND DATE_FORMAT(date_start, '%Y-%m') = :start_date";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':lead_id' => $lead_id,
            ':start_date' => $start_date
        ]);
        return $stmt->fetch(PDO::FETCH_ASSOC);

    }
    
}