<?php   

const SEGMENTS = array(
    'viewed.paid' => 21,
    'viewed.unpaid' => 23,
    'selected.paid' => 24,
    'selected.unpaid' => 25,
    'interview.paid' => 20,
    'interview.unpaid' => 22,
    'test.paid' => 27,
    'test.unpaid' => 28,
    'voucher.unpaid' => 26
);

class QueueCampaign {

    private $conn;

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

    function queue($lead_id, $action) {
            
        $sql = "SELECT * FROM leads WHERE id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute([ $lead_id ]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        $user_type = ($user['signature_id'] && $user['signature_status'] === 'ACTIVE') ? 'paid' : 'unpaid';
        $action_type = "$action.$user_type";
        $segment_id = SEGMENTS[$action_type];
        
        // file_put_contents('DadosSegmentos.txt', 'Tipo: '.$user_type.PHP_EOL, FILE_APPEND);
        // file_put_contents('DadosSegmentos.txt', 'Ação: '.$action_type.PHP_EOL, FILE_APPEND);
        // file_put_contents('DadosSegmentos.txt', 'Segmento: '.$segment_id.PHP_EOL, FILE_APPEND);

        $sql = "DELETE FROM lead_lists_leads WHERE leadlist_id = ? AND lead_id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute([ $segment_id, $lead_id ]);

        //file_put_contents('ERROR2.txt', print_r($stmt->errorInfo(), true)."$sql {$segment_id} $lead_id");    

        $sql = "DELETE campaign_leads FROM campaign_leads
            LEFT JOIN campaign_leadlist_xref ON campaign_leadlist_xref.campaign_id = campaign_leads.campaign_id
            WHERE campaign_leads.lead_id = ? AND campaign_leadlist_xref.leadlist_id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute([ $lead_id, $segment_id ]);

        //file_put_contents('SQL.txt', "$sql {$campaign->campaign_id} $lead_id");
        
        
        $sql = "INSERT INTO lead_lists_leads(leadlist_id, lead_id, date_added, manually_removed, manually_added) 
            VALUES(:leadlist_id, :lead_id, NOW(), 0, 1) ON DUPLICATE KEY UPDATE date_added = NOW()";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute([
            ':leadlist_id' => $segment_id,
            ':lead_id' => $lead_id
        ]);
        

    }

}