<?php 
if (isset($_POST) == true) {
    require_once("hivasok.php");

    $config['db_host'] = 'localhost';
    $config['db_user'] = 'cadline';
    $config['db_pass'] = 'Shea6hoo';
    $config['db_name'] = 'cl_hlusers';

    $msh = new hivasok();
    $msh->init($config['db_host'], $config['db_name'], $config['db_user'], $config['db_pass']);

    $cntry = $_POST['orszag'];
    $email = $_POST['email'];

    $felhasznalo = "SELECT `nUserID` FROM `u_emails` WHERE `email` = '".$email."' limit 1";
    $msh->query($felhasznalo);
    $felh = $msh->fetchNext();
    $user = $felh['nUserID'];

    $msh->query("SELECT `order` FROM `o_orders` WHERE `country` = '{$cntry}' ORDER BY `id` DESC limit 1");
    $order=$msh->fetchNext();
    $orderNumber = $order['order'];

    $kezdo = strpos($orderNumber, "-")+1;
    $veg = strpos($orderNumber, "/")-2;
    $szam = (int)substr($orderNumber, $kezdo, $veg);
    $prOrderNumber = "E-".$szam."/".date("Y");

    $msh->query("SELECT `ctrNameEng` FROM `countries` WHERE `ctrID` = '{$cntry}'");
    $ctryName = $msh->fetchNext();
    $orszagNev = $ctryName['ctrNameEng'];

    $fileName = $_FILES["file"]["name"];
    $targetDir = "../../";
    $targetFilePath = $targetDir.$fileName;

    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
    $allowTypes = array('jpg', 'png', 'jpeg', 'gif', 'pdf', 'docx', 'doc', 'txt', 'bmp');

    if (in_array($fileType, $allowTypes)) {
        if (!move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) {
            $eredmeny['hiba'] = "Error in file uploading";
            echo json_encode($eredmeny);
            return false;
        }
    } else {
        $eredmeny['hiba'] = "Unknown file extension";
        echo json_encode($eredmeny);
        return false;
    }

    $to = 'office@cadline.hu';
    $from = 'partnering@archlinexp.com';
    $fromName = 'ARCHLineXP Retail Store';
    $subject = 'Attachment for order: '.$orszagNev.' '.$prOrderNumber;
    $file = $targetFilePath;
    $htmlContent = '<h1>'.$_POST['file_info'].'</h1>';
    $headers = "From: $fromName"." <".$from.">";
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
    $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
        "Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";

    if (!empty($file) > 0){
        if(is_file($file)){
            $message .= "--{$mime_boundary}\n";
            $fp =    @fopen($file,"rb");
            $data =  @fread($fp,filesize($file));

            @fclose($fp);
            $data = chunk_split(base64_encode($data));
            $message .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\n" .
                "Content-Description: ".basename($files[$i])."\n" .
                "Content-Disposition: attachment;\n" . " filename=\"".basename($file)."\"; size=".filesize($file).";\n" .
                "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
        }
    }
    
    $returnpath = "-f" . $from;

    if ($cntry != '37') {
        $mail = @mail($to, $subject, $message, $headers, $returnpath);
    }

    if (function_exists('curl_file_create')) {
        $cFile = curl_file_create($file, $_FILES[$name]['type'], basename($file));

        $post = [
            'file_content'  => $cFile,
            'action'        => 'uploadFile',
            'nUserID'       => $user,
            'file_info'     => $_POST['file_info']
        ];

        $login      = 'mate.nagy@cadline.hu';
        $password   = 'Mng67otf';
        $url        = 'https://crm.cadline.hu/imre.php';
        $ch         = curl_init();

        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");

        $result = curl_exec($ch);

        curl_close($ch);


        $eredmeny['sikeres'] = 'true';
    }

    unlink($targetFilePath);

    echo json_encode($eredmeny);
}
?>