<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

include_once __dir__ . "/../vendor/autoload.php";

class Google extends Core {
    
    private $client; 
    private $service;

    public function setAccessToken($token_access, $token_refresh) {
        try {
            
            if(empty($token_access) || empty($token_refresh)){
                throw new Exception('Tokens estão vazios - Token Access ou Token Refresh. Por favor, renove o token.');
            }
             
            // Configure o token com ambos access_token e refresh_token
            $accessToken = [
                'access_token' => $token_access,
                'refresh_token' => $token_refresh,
                'expires_in' => 3600,
                'created' => time()
            ];
            
            $this->client->setAccessToken($accessToken); 
            
            // Verifica se o token está expirado
            if ($this->client->isAccessTokenExpired()) {
                if ($this->client->getRefreshToken()) {
                    // Renova o token utilizando o refresh token
                    $newToken = $this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
    
                    $token_acess = $newToken['access_token'];
                    if (isset($newToken['refresh_token'])) {
                        $token_refresh = $newToken['refresh_token'];
                    }
                    
                    // Configure o token com ambos access_token e refresh_token
                    $accessToken = [
                        'access_token' => $token_access,
                        'refresh_token' => $token_refresh,
                        'expires_in' => 3600,
                        'created' => time()
                    ];
                    
                    $this->client->setAccessToken($accessToken);

                } else {
                    throw new Exception('Token de acesso expirado e não há refresh token disponível. Por favor, renove o token.');
                }
            }
    
            // Inicializar o serviço do Google Calendar com o cliente autenticado
            $this->service = new Google_Service_Calendar($this->client);
        } catch (Exception $e) {
            return ['type' => 'FAIL', 'message' => $e->getMessage()];
        }
    }
    
    function getUserInvite($leads = null) {
        if (is_null($leads)) {
            $decodedData = json_decode($_POST['leads'], true);
    
            if (!isset($decodedData) || !is_array($decodedData)) {
                return ['type' => 'FAIL', 'message' => 'Invalid input or no leads provided'];
            }
    
            $leads = $decodedData;
        } else {
            $decodedData = json_decode($leads, true);
    
            if (!isset($decodedData) || !is_array($decodedData)) {
                return ['type' => 'FAIL', 'message' => 'Invalid input or no leads provided'];
            }
    
            $leads = $decodedData;
        }
    
        if (empty($leads)) {
            return ['type' => 'FAIL', 'message' => 'No leads provided'];
        }
    
        $lead_ids = array_column($leads, 'lead_id');
        $placeholders = implode(',', array_fill(0, count($lead_ids), '?'));
    
        $sql = "SELECT id, email 
                FROM `leads` 
                WHERE id IN ($placeholders)";
    
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute($lead_ids);
     
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        return ['type' => 'OK', 'data' => $results];
    }
    
    public function storeToken() {
        
        $code = $_POST['code']; // Receber o authorization code
        
        // Endpoint para troca do authorization code por tokens
        $url = 'https://oauth2.googleapis.com/token';
        
        $postData = [
            'grant_type' => 'authorization_code',
            'code' => $code,
            'client_id' => '563429419603-sk5hs3ad2pepeiupsdegnbkgi096lbma.apps.googleusercontent.com',
            'client_secret' => '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',
            'redirect_uri' => 'https://memprega.com.br', // Deve ser consistente com o registro no Google Console 
        ];
        
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        
        $response = curl_exec($ch);
        
        if (curl_errno($ch)) {
            return ['type' => 'FAIL', 'message' => 'Erro cURL: ' . curl_error($ch)];
        }
        
        curl_close($ch);
         
        $tokenInfo = json_decode($response, true);
         
        if (isset($tokenInfo['error'])) {
            return ['type' => 'FAIL', 'message' => 'Erro ao obter access token: ' . $tokenInfo['error_description']];
        }
        
        return ['type' => 'OK', 'access' => $tokenInfo['access_token'], 'refresh' => $tokenInfo['refresh_token'], 'message' => 'Access token armazenado com sucesso'];
    }

    
    public function createEvent() {
        // Decodificar os dados recebidos do frontend
        $access = $_POST['access'];
        $refresh = $_POST['refresh'];
        $interview_id = $_POST['id'];
        $leads = json_decode($_POST['leads'], true);
        $user_email = $_POST['companie_mail'];
    
        if (empty($leads) || !$user_email) {
            return [
                'type' => 'FAIL',
                'message' => 'Dados insuficientes. Certifique-se de enviar os leads e o email do recrutador.',
            ];
        }
        
        // Configurar o token no cliente do Google
        $this->client = new Google_Client();
        $this->client->setApplicationName('Integração com Google Calendar');
        $this->client->setAccessType('offline');
        $this->client->addScope(Google_Service_Calendar::CALENDAR);
        $setTokenResult = $this->setAccessToken($access, $refresh);

        if (isset($setTokenResult['type']) && $setTokenResult['type'] === 'FAIL') {
            return $setTokenResult; // Retorna o erro se o token não for válido
        }
    
        // Obter os e-mails dos candidatos com base no lead_id
        $inviteData = $this->getUserInvite(json_encode($leads));
    
        if ($inviteData['type'] !== 'OK') {
            return $inviteData;
        }
    
        // Mapear os e-mails retornados aos IDs dos leads
        $emailsById = [];
        foreach ($inviteData['data'] as $item) {
            $emailsById[$item['id']] = $item['email'];
        }
    
        $results = []; // Array para armazenar o resultado de cada evento
        foreach ($leads as $lead) {
            
             $existingMeetCount = $this->getCountLinkMeet($lead['lead_id'], $interview_id);
        
            // Se já existe um link_meet, pula esse lead
            if ($existingMeetCount > 0) {
                continue;
            }
            
            $candidate_email = $emailsById[$lead['lead_id']] ?? null;
    
            if (!$candidate_email) {
                $results[] = [
                    'type' => 'FAIL',
                    'message' => "Nenhum e-mail encontrado para o lead ID {$lead['lead_id']}",
                ];
                continue;
            }
    
            // Configurar os dados do evento
            $event = new Google_Service_Calendar_Event([
                'summary' => 'Entrevista de Trabalho',
                'description' => 'Entrevista online pelo Google Meet.',
                'start' => [
                    'dateTime' => "{$lead['date']}T{$lead['timeAt']}:00-03:00",
                    'timeZone' => 'America/Sao_Paulo',
                ],
                'end' => [
                    'dateTime' => "{$lead['date']}T{$lead['timeEnd']}:00-03:00",
                    'timeZone' => 'America/Sao_Paulo',
                ],
                'attendees' => [
                    ['email' => $candidate_email],
                    ['email' => $user_email],
                ],
                'conferenceData' => [
                    'createRequest' => [
                        'requestId' => uniqid(),
                    ],
                ],
            ]);
    
            try {
                $calendarId = 'primary';
                $createdEvent = $this->service->events->insert($calendarId, $event, ['conferenceDataVersion' => 1, 'sendUpdates' => 'all']);
                $results[] = [
                    'type' => 'OK',
                    'message' => 'Evento criado com sucesso!',
                    'eventLink' => $createdEvent->htmlLink,
                    'meetLink' => $createdEvent->conferenceData->entryPoints[0]->uri,
                    'candidate' => $candidate_email,
                    'lead_id' => $lead['lead_id'],
                ];
                
                // Atualizar a tabela process_list_interview_sessions
                $updateSql = "UPDATE process_list_interview_sessions
                              SET link_meet = :link_meet
                              WHERE lead = :lead AND process_list_interview = :process_list_interview";
                
                $updateStmt = parent::$conn->prepare($updateSql);
                $updateStmt->bindValue(':link_meet', $createdEvent->conferenceData->entryPoints[0]->uri, PDO::PARAM_STR);
                $updateStmt->bindValue(':lead', $lead['lead_id'], PDO::PARAM_INT);
                $updateStmt->bindValue(':process_list_interview', $interview_id, PDO::PARAM_INT);
                
                $updateStmt->execute();
                
            } catch (Exception $e) {
                $results[] = [
                    'type' => 'FAIL',
                    'message' => "Erro ao criar o evento para o lead ID {$lead['lead_id']}: " . $e->getMessage(),
                ];
            }
        }
    
        // Retornar o resumo dos resultados
        return [
            'type' => 'OK',
            'results' => $results,
        ];
    }

    
    public function getCountLinkMeet($lead_id, $interview_id) {
        $sql = "SELECT COUNT(*) FROM process_list_interview_sessions 
                WHERE lead = :lead_id 
                AND process_list_interview = :interview_id 
                AND link_meet IS NOT NULL AND link_meet != ''";
        
        $stmt = parent::$conn->prepare($sql);
        $stmt->bindValue(':lead_id', $lead_id, PDO::PARAM_INT);
        $stmt->bindValue(':interview_id', $interview_id, PDO::PARAM_INT);
        
        $stmt->execute();
        
        return $stmt->fetchColumn();
    } 

}