<?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' => 26
    );

    class ProcessListAction extends Core {

        function save() {
           
            
            $process_list = $_POST['processList'];
            $leads = json_decode($_POST['leads'], true);
            $action = $_POST['action'];
                
                $sql = "INSERT INTO process_list_lead_actions(action, lead, process_list) VALUES(?, ?, ?) 
                    ON DUPLICATE KEY UPDATE frequency = frequency + 1, last_update = NOW()";
    
                $campaign = new QueueCampaign($this->getConnection());
                $candidates_email = array();
                
                foreach($leads as $lead) {
                   
                        $stmt = parent::$conn->prepare($sql);
                        
                        file_put_contents("post.log",print_r($sql,true),FILE_APPEND);
                         file_put_contents("post.log",print_r($action,true),FILE_APPEND);
                          file_put_contents("post.log",print_r($lead,true),FILE_APPEND);
                           file_put_contents("post.log",print_r($process_list,true),FILE_APPEND); 
                           
                        $stmt->execute([ $action, $lead, $process_list ]);
                        if($action !== 'searched')
                            $candidates_email[] = array('lead' => $lead);
                            $campaign->queue($lead, $action);
                    
                    
                }
    
                if(sizeof($candidates_email)) {
    
                    $sender = new SendEmail($this->getConnection());
                    foreach($candidates_email as $email)
                        $sender->sendForProcessList($email['lead'], $action, [], $process_list, $action !== 'searched');
    
                }
                
            

            return [ 'type' => 'OK' ];

        }
        
        function list() {

            $lead = $_GET['id'];
            $sql = "SELECT count(*) as total, action, last_update FROM process_list_lead_actions WHERE lead = ? GROUP BY action";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([ $lead ]);
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            return [ 'type' => 'OK', 'data' => $result ];

        }

    }