<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

//Load Composer's autoloader
require 'vendor/autoload.php';

// Database connection
$servername = "localhost";  
$username = "hiretokd_slickwebstudio"; 
$password = "Jbn{01I(]Vu9";  
$dbname = "hiretokd_slickwebstudio";  

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$web_url = 'https://slickwebstudios.com';
$domain_name = 'slickwebstudios';

$data = $_POST;
// $jsonData = json_encode($data);
$jsonData = base64_encode(json_encode($data));

if (!empty($data)) {
    // Sanitize data for database insertion
    $jsonData = $conn->real_escape_string($jsonData);

    $sql = "INSERT INTO leads(leads) VALUES('$jsonData')";
    if ($conn->query($sql) === TRUE) {
        // Data inserted successfully
    } else {
        // Handle database error
    }
}

if(!empty($_POST['email']) && isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] == $web_url){


    $table_style = "style='border:1px solid; padding:10px;'";
    $row_style = "style='border-bottom:1px solid;'";
    
    $brand_name = "Slick Web Studios";
    $to = "leads@slickwebstudios.com";
    $from = "info@slickwebstudios.com";
    $from_pass = "info@slickwebstudios.com";
    
    $subject = $brand_name." Lead";
    
    $exclude = array('pc','phone','g-recaptcha-response','pop_form');
    
    if(!empty($_POST['pc']) && !empty($_POST['phone'])){
        $phone = $_POST['pc'].'-'.$_POST['phone'];
    }else{
        $phone = $_POST['phone'];
    }
    
    
    foreach($_POST as $key => $val){
        if(!empty($val)){
            if(is_array($val)){
                $c = 1;
                foreach($val as $this_key => $this_val){
                    $val_res = preg_replace('/[^\da-z@.\-:\/ ]/i', '', $this_val);  // Updated regex
                    $post_data[$key.'_'.$c] = $val_res;
                    $c++;
                }
            } else {
                $val_res = preg_replace('/[^\da-z@.\-:\/ ]/i', '', $val);  // Updated regex
                $post_data[$key] = $val_res;
            }
        }
    }


    

    $message = "<html>
                    <head>
                        <title>".$subject."</title>
                    </head>
                    <body>
                        <table ".$table_style.">
                        <tr ".$row_style.">
                            <th>Phone</th>
                            <th>".$phone."</th>
                        </tr>
                        ";
                        foreach($post_data as $key => $val){
                            if($val != "" && in_array($key,$exclude) == false){
                                $message .= "
                                <tr ".$row_style.">
                                    <th>".ucfirst(str_replace("_"," ",$key))."</th>
                                    <th>".$val."</th>
                                </tr>
                                ";
                            }
                        }
                            
    $message .= "        </table>
                    </body>
                </html>";
    
   

    //Create an instance; passing `true` enables exceptions
    $mail = new PHPMailer(true);

    try {
        

        //Server settings
        //$mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
        $mail->isSMTP();                                            //Send using SMTP
        
        //$mail->Host       = 'talenttube.io';                     //Set the SMTP server to send through
        $mail->Host       = 'premium112.web-hosting.com ';                     //Set the SMTP server to send through
        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
        $mail->Username   = $from;                     //SMTP username
        $mail->Password   = 'U27]?yPfwlIE';                               //SMTP password

        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
        $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

        //Recipients
        $mail->setFrom($from, $brand_name);
        $mail->addAddress($to, $brand_name);     //Add a recipient
        //$mail->addAddress('ellen@example.com');               //Name is optional
        $mail->addReplyTo($from, 'Reply');
        $mail->addCC($from);
        //$mail->addBCC('bcc@example.com');

        //Attachments
        //$mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
        //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

        //Content
        $mail->isHTML(true);                                  //Set email format to HTML
        $mail->Subject = $subject;
        $mail->Body    = $message;
        //$mail->AltBody = $customer_email;

        $mail->send();

        /*header('Location: thank_you.php');*/

    } catch (Exception $e) {
        echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
    
    
    /* ==================== API CALL =================== */
    
    if(isset($_POST['first_name']) && isset($_POST['last_name'])){
        $full_name = $_POST['first_name'].' '.$_POST['last_name'];
    }else{
        $full_name = (!empty($_POST['full_name']))? $_POST['full_name']:'-';
    }
    
    $email = (!empty($_POST['email']))? $_POST['email']:'-';
    $package_id = (!empty($_POST['pkg']))? $_POST['pkg']:'-';
    $tracker = (!empty($_POST['form_name']))? $_POST['form_name']:'-';
    $lead_source = (!empty($_POST['lead_source']))? $_POST['lead_source']:'-';
    $message = (!empty($_POST['message']))? $_POST['message']:'-';
    
    
    
    $api_exclude = array('pkg','full_name','first_name','last_name','email','form_name','lead_source','message','pc','phone');
    
        $extra_data_list = '';
        foreach($post_data as $key => $val){
            if(in_array($key,$api_exclude) == false){
                $extra_data_list .= $key.':'.$val.',';
            }
        }
    
        $extra_info = rtrim($extra_data_list,',');
    
        $postRequest = array(
            'Name' => $full_name,
            'Email' => $email,
            'call_name' => 'add_lead',
            'Phone' => $phone,
            'package_id' => $package_id,
            'tracker' => $tracker,
            'message' => $message,
            'lead_source' => $lead_source,
            'extra_info' => $extra_info,
        );
    
    $cURLConnection = curl_init("https://crm.vurkflow.com/{$domain_name}/createlead/");
    curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $postRequest);
    $apiResponse = curl_exec($cURLConnection);
    curl_close($cURLConnection);
    
    // echo $apiResponse;
    // die();
    
    header('Location: thankyou.php');
    
    
    
}




?>