<?php
include_once __dir__ .  '/../core/Filter.php';
include_once __dir__ .  '/../core/LogEvent.php';

class Boost extends Core
{
    use Filter;
    
    function saveCampaign(){ 
        
        if (empty($_POST['processId']) || empty($_POST['userId'])) { 
            return ['type' => 'ERROR', 'message' => 'Parâmetros obrigatórios ausentes: processId ou userId'];
        }
        $companyId  = $_POST['company_id'];    
        $process_id = $_POST['processId'];
        $lead_id    = $_POST['userId'];
        $paid       = isset($_POST['paid']) ? $_POST['paid'] : false;
        
        if($paid){
            $status = 'pending';
        }else{
            $status = 'new';
        }
    
        $sql = "
            SELECT 
                c.owner_id
            FROM 
                process_list pl
            INNER JOIN 
                companies c ON pl.company = c.id
            WHERE 
                pl.id = :id
        ";
    
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':id' => $process_id
        ]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
        if ($result && isset($result['owner_id'])) {
            
            $insertSql = "
                INSERT INTO campaign_process_list (
                    process_list,
                    lead_id,
                    owner_id,
                    date_added,
                    status
                ) VALUES (
                    :process_list,
                    :lead_id,
                    :owner_id,
                    NOW(),
                    :status
                )
            ";
    
            $insertStmt = parent::$conn->prepare($insertSql);
            if($insertStmt->execute([
                ':process_list' => $process_id,
                ':lead_id'      => $lead_id,
                ':owner_id'     => $result['owner_id'],
                ':status'       => $status
            ])){
                
                if(!$paid){
                    $sql = "INSERT INTO plans_credits (company_id, use_credit)
                    VALUES (:id, 1)
                    ON DUPLICATE KEY UPDATE use_credit = use_credit + 1";
                    $stmt = parent::$conn->prepare($sql);
                    $stmt->execute([':id' => $companyId]);
                }
                
                return ['type' => 'OK'];
        
            }
        } else {
            return ['type' => 'FAIL'];
        }
    }
    
    function listCampaign(){
        $sql = "SELECT
            cpl.*,
            DATE_FORMAT(cpl.date_added, '%d/%m/%Y') AS date_added,
            pl.name AS process_name,
            pl.companyname,
            pl.company AS company_id,
            c.companyemail,
            CONCAT(u.first_name, ' ', u.last_name) AS seller
        FROM
            campaign_process_list cpl
        INNER JOIN
            process_list pl ON cpl.process_list = pl.id
        INNER JOIN
            users u ON cpl.owner_id = u.id
        INNER JOIN
            companies c ON pl.company = c.id
        ORDER BY
            cpl.id DESC;";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
   
        if ($result) {
            return ['type' => 'OK', 'data' => $result];
        } else {
            return ['type' => 'FAIL'];
        }
    }
    
    function updateCampaign(){ 
        
        if (empty($_POST['id'])) { 
            return ['type' => 'ERROR', 'message' => 'Parâmetros obrigatórios ausentes: id'];
        }
        
        $id = $_POST['id'];
        $status = $_POST['status'];
        $date_start = $_POST['date_start'] ?? null;
        $date_end = $_POST['date_end'] ?? null;
        $num_candidate = $_POST['num_candidate'] ?? null;
        $num_views = $_POST['num_views'] ?? null;
        $num_clicks = $_POST['num_clicks'] ?? null; 
        $used_credit = $_POST['used_credit'] ?? null;
        $observation = $_POST['observation'] ?? null;
        $contract_end_date = (new DateTime($date_start))->modify('+7 days')->format('Y-m-d');

        
        $sql = "UPDATE campaign_process_list SET status = :status, date_start = :date_start, date_end = :date_end, num_candidate = :num_candidate, num_views = :num_views, num_clicks = :num_clicks, used_credit = :used_credit, observation = :observation, contract_end_date = :contract_end_date WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':status' => $status,
            ':date_start' => $date_start,
            ':date_end' => $date_end,
            ':num_candidate' => $num_candidate,
            ':num_views' => $num_views,
            ':num_clicks' => $num_clicks,
            ':used_credit' => $used_credit,
            ':observation' => $observation,
            ':contract_end_date' =>$contract_end_date,
            ':id' => $id
        ]);
    
        if ($stmt->rowCount() > 0) {
            return ['type' => 'OK'];
        } else {
            return ['type' => 'FAIL', 'message' => 'Nenhuma alteração realizada'];
        }
    }
    
    function highlightCampaign(){ 
        $sql = "SELECT 
			pl.id,
			pl.company,			
            pl.name,
			pl.companyname,
			pl.salary,
			pl.modalityjob,
            pl.workregime,
            pl.description,
            pl.start_monday,
            pl.end_monday,
            pl.benefits,
            pl.requirements,
            pl.activities
        FROM 
            campaign_process_list cpl
        INNER JOIN 
            process_list pl ON cpl.process_list = pl.id
        INNER JOIN 
            users u ON cpl.owner_id = u.id
        WHERE cpl.status = 'active'    
        ORDER BY 
            cpl.date_added DESC";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        if ($result) {
            return ['type' => 'OK', 'data' => $result];
        } else {
            return ['type' => 'FAIL'];
        }
    }  
    
    function removeCampaign(){
        if (empty($_POST['id'])) { 
            return ['type' => 'ERROR', 'message' => 'Parâmetros obrigatórios ausentes: id'];
        }
        
        $id = $_POST['id'];
        $sql = "DELETE FROM `campaign_process_list` WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        if($stmt->execute([':id' => $id])){
            return ['type' => 'OK'];
        } else {
            return ['type' => 'FAIL'];
        }
    }
    
    function isCampaignExpired() {
        if (empty($_POST['id'])) { 
            return ['type' => 'ERROR', 'message' => 'Parâmetro obrigatório ausente: id'];
        }
        
        $id = $_POST['id'];
        
        $sql = "SELECT 
                    CASE 
                        WHEN NOT EXISTS (
                            SELECT 1 
                            FROM campaign_process_list cpl 
                            WHERE cpl.process_list = :id
                        ) THEN 1
                        WHEN EXISTS (
                            SELECT 1 
                            FROM campaign_process_list cpl 
                            WHERE cpl.process_list = :id
                              AND cpl.status <> 'finish'
                        ) THEN 0
                        ELSE 1
                    END AS expired";
        
        $stmt = parent::$conn->prepare($sql);
        
        if ($stmt->execute([':id' => $id])) {
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($result) {
                $isExpired = (bool) $result['expired']; // retorna true ou false
                return ['type' => 'OK', 'data' => $isExpired];
            } else {
                // Se der algum problema inesperado, considerar como expirado
                return ['type' => 'OK', 'data' => true];
            }
        } else {
            return ['type' => 'FAIL'];
        }
    }

    function listCompleteCampaign(){ 
        $sql = "SELECT 
            pl.id,
            pl.company,			
            pl.name,
            pl.companyname,
            pl.salary,
            pl.modalityjob,
            pl.workregime,
            pl.description,
            pl.start_monday,
            pl.end_monday,
            pl.benefits,
            pl.requirements,
            pl.activities
        FROM campaign_process_list cpl
        INNER JOIN process_list pl ON cpl.process_list = pl.id
        INNER JOIN users u ON cpl.owner_id = u.id
        INNER JOIN (
            SELECT process_list, MAX(date_added) AS max_date
            FROM campaign_process_list
            GROUP BY process_list
        ) latest ON latest.process_list = cpl.process_list 
                AND latest.max_date = cpl.date_added
        ORDER BY cpl.date_added DESC;
        ";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        if ($result) {
            return ['type' => 'OK', 'data' => $result];
        } else {
            return ['type' => 'FAIL'];
        }
    }

}