<?php 

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

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;

    class SendEmail {

        private $conn;

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

        function sendForProcessList($lead_id, $template, $params = [], $process_list_id = null, $only_paid = true) {

            $sql = "SELECT * FROM process_list_lead_email WHERE process_list = ? AND lead = ? AND action = ?";
            $stmt = $this->conn->prepare($sql);            
            $stmt->execute([ $process_list_id, $lead_id, $template ]);
            $email = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if($email) {

                $email_lasttime = new DateTime($email['send_time']);
                $timenow = new DateTime();

                $diff = $timenow->diff($email_lasttime);
                if($diff->h < 24)
                    return;

            }
            
            /*$sql = "SELECT voucher FROM companies AS A1
                LEFT JOIN process_list AS A2 ON A2.company = A1.id
                WHERE A2.id = ?";
            $stmt = $this->conn->prepare($sql);            
            $stmt->execute([ $process_list_id ]);            
            $process_list = $stmt->fetch(PDO::FETCH_ASSOC);             */

            $sql = "SELECT * FROM leads WHERE id = ?";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute([ $lead_id ]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            /*if($only_paid && $user['signature_id'] === null)
                return;*/

            //$user_type = ($user['signature_id'] || $process_list['voucher']) ? 'paid' : 'unpaid';
            $user_type = ($user['signature_status'] === 'ACTIVE') ? 'paid' : 'unpaid';

            $content = file_get_contents(__dir__ . "/templates/$template.$user_type.html");
            
            foreach($params as $key=>$value)
                $content = str_replace("#{$key}", $value, $content);         

            $content = str_replace("#{fullname}", $user['firstname'], $content);
            //$content = str_replace("#{voucher}", $process_list['voucher'], $content);

            //$this->send($user['email'], $user['firstname'], $content);

            $sql = "INSERT IGNORE INTO process_list_lead_email(process_list, lead, action) VALUES(?, ?, ?)";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute([                
                $process_list_id,
                $user['id'],
                $template
            ]);

        }

        function sendForTest($lead, $process_list, $test_id, $params = []) {

            $sql = "SELECT * FROM leads WHERE id = ?";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute([ $lead ]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            $user_type = ($user['signature_status'] === 'ACTIVE') ? 'paid' : 'unpaid';
            
            $content = file_get_contents(__dir__ . "/templates/test.$user_type.html");
            
            foreach($params as $key=>$value)
                $content = str_replace("#{$key}", $value, $content);

            $content = str_replace("#{fullname}", $user['firstname'], $content);

            //$this->send($user['email'], $user['firstname'], $content);

            $sql = "INSERT INTO process_list_lead_email(process_list, lead, action) VALUES(?, ?, ?)";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute([
                $process_list,
                $user['id'],
                "test:$test_id"
            ]);

            //$this->sendVoucher($process_list, $lead);

        }

        function sendForInterview($lead, $interview_id, $params = []) {

            $sql = "SELECT * FROM leads WHERE id = ?";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute([ $lead ]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            $user_type = ($user['signature_status'] === 'ACTIVE') ? 'paid' : 'unpaid';
            $content = file_get_contents(__dir__ . "/templates/interview.$user_type.html");
            
            foreach($params as $key=>$value)
                $content = str_replace("#{$key}", $value, $content);
            
            $content = str_replace("#{fullname}", $user['firstname'], $content);

            //$this->send($user['email'], $user['firstname'], $content);

            $sql = "SELECT * FROM process_list_interviews WHERE id = ?";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute([ $interview_id ]);
            $interview = $stmt->fetch(PDO::FETCH_ASSOC);

            $sql = "INSERT INTO process_list_lead_email(process_list, lead, action) VALUES(?, ?, ?)";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute([                
                $interview['process_list'],
                $user['id'],
                "interview:$interview_id"
            ]);

            //$this->sendVoucher($interview['process_list'], $lead);

        }

        private function sendVoucher($process_list_id, $lead_id) {

            $sql = "SELECT * FROM leads WHERE id = ?";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute([ $lead_id ]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if($user['signature_id'])
                return;

            $sql = "SELECT voucher FROM companies AS A1
            LEFT JOIN process_list AS A2 ON A2.company = A1.id
            WHERE A2.id = ?";
            $stmt = $this->conn->prepare($sql);
            $stmt->execute([ $process_list_id ]);
            $process_list = $stmt->fetch(PDO::FETCH_ASSOC);

            if($process_list['voucher'] === null)
                return;

            $content = file_get_contents(__dir__ . "/templates/voucher.html");

            $content = str_replace("#{fullname}", $user['firstname'], $content);
            $content = str_replace("#{voucher}", $process_list['voucher'], $content);

            //$this->send($user['email'], $user['firstname'], $content);
            

        }

        function sendWelcome($email) {

            $content = file_get_contents(__dir__ . "/templates/welcome.html");
            //$this->send($email, null, $content);

        }

        public function send($email, $firstname, $content, $subject = 'Nova mensagem do Memprega') {

            try {

                $mail = new PHPMailer(true);                
                $mail->isSMTP();                                            // Send using SMTP
                $mail->Host       = 'memprega.com.br';                    // Set the SMTP server to send through
                $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
                $mail->Username   = 'memprega@memprega.com.br';                     // SMTP username
                $mail->Password   = 'memprega@19812';                               // SMTP password
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
                $mail->Port       = 465;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
                $mail->CharSet    = 'UTF-8';
                //Recipients
                $mail->setFrom('memprega@memprega.com.br', 'Memprega');
                $mail->addAddress($email, $firstname);

                $mail->isHTML(true);                                  // Set email format to HTML
                $mail->Subject = $subject;
                $mail->Body    = $content;
                $mail->send();                

            } catch(Exception $e) {
                file_put_contents('mail.error.txt', "Message could not be sent. Mailer Error: {$mail->ErrorInfo}");
            }

        }

    }