<?php

function orderFromErp($erpApiLink, $data = 0) {
    $apiKey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IndlYkFwaTgiLCJwYXNzd29yZCI6ImV5OHlydzRyIn0.UyShdlXVpL0u7zV-QJKYqg67JRO0IrJSgaO67rvi0hY';
    try {
        $ch = curl_init('localhost/erp/controllers/api_web.php?do=' . $erpApiLink);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($data != 0) {
            curl_setopt($ch, CURLOPT_POST, true);
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Accept: application/json',
            "Open-Key:  $apiKey")); // Inject the token into the;
        $response = curl_exec($ch);
//        print_r($response);
        curl_close($ch);
//        if (curl_errno($ch)) {
//            echo 'Curl error: ' . curl_error($ch);
//        }
        return $response;
    } catch (Exception $ex) {
        echo -1;
    }
}



function getPatientLink($dataArray) {
    $url = 'http://api.naslab.gt4it.com/api/patient';
    $data = array(
        'name' => $dataArray['name']
        , 'patient_id' => $dataArray['patient_id']
        , 'age' => $dataArray['age']
        , 'sex' => $dataArray['sexTxt']
        , 'phone' => $dataArray['phone']
    );

    // $apiKey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJuYXMtbGFiIiwiYXVkIjoibmFzLWxhYiIsImp0aSI6ImZLb2tpeEw5UloiLCJpYXQiOjE3MDU2NTc5MjAuMjEzNjk1fQ.9N4Vi0cq5JFM4maBEKPCtElbLEtk3CHXQZJDtm1xECM';
    $apiKey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJuYXMtbGFiIiwiYXVkIjoibmFzLWxhYiIsImp0aSI6IlhhUG5jWk9NNUciLCJpYXQiOjE3MTcwODE1NjMuNzUyODkxfQ.afHJiQtwldT_nNjUrt_WESapqCl5YyOWl_vUEHTJchI';

  //   print_r($dataArray);


    // Initializes a new cURL session
    $curl = curl_init($url);
//    print_r($curl);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    // 1. Set the CURLOPT_RETURNTRANSFER option to true
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// 2. Set the CURLOPT_POST option to true for POST request
    curl_setopt($curl, CURLOPT_POST, true);
// 3. Set the request data 
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// 4. Set  headers for API Auth 

    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        //'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
        'AuthorizationKey: Bearer ' . $apiKey
    ));

    // Execute cURL request with all previous settings
    $response = curl_exec($curl);

    if (curl_errno($curl)) {
        $error_msg = curl_error($curl);
    }
   //  print_r($error_msg);
    // Close cURL session
    curl_close($curl);

    //  echo $response . PHP_EOL;

    $res = json_decode($response);

//    print_r($res);
//    print_r($res->success);
//    print_r($res->error);

  if ($res->success) {
            $link = $res->data->anatomy_url;
    } else {
        $link = -1;
//        return $res->error->message;
    }

    r::exec(' update patients set inv_link = ? where id = ? ', [$link, $dataArray['patient_id']]);
    return $link;
}


function getPatientDataArr($patient) {
    $date = $patient->dateofbirth;
    $ageNet = 0;
    if ($date == '0000-00-00' || is_null($date) || $date == '') {
        $age = 0;
    } else {
## calculate wife age
        $dateWife = new DateTime($date);
        $today1 = new DateTime(date('Y-m-d'));
        $interval = $today1->diff($dateWife);
    }

    if ($interval->y > 0) {
        $ageAll = $interval->y . ' Years';
        $age = $interval->y;
        $ageNet = $interval->y;
        $ageUnit = 1;
    } elseif ($interval->m > 0) {
        $ageAll = $interval->m . ' Months';
        $age = $interval->m;
        $ageUnit = 2;
    } elseif ($interval->d >= 0) {
        $ageAll = 1 + $interval->d . ' Days';
        $age = 1 + $interval->d;
        $ageUnit = 3;
    }


    if ($patient->gender == 1) {
        $sex = 'Male';
    } else {
        $sex = 'Female';
    }



    $dataArray = array();
    $dataArray['name'] = $patient->wifename;
    $dataArray['patient_id'] = $patient->id;
    $dataArray['ageAll'] = $ageAll;
    $dataArray['age'] = $ageNet;
    $dataArray['sex'] = $patient->gender;
    $dataArray['sexTxt'] = $sex;
    $dataArray['referred_by'] = 1;
    $dataArray['phone'] = $patient->phone;
    $dataArray['inv_link'] = $patient->inv_link;


    return $dataArray;
}



function generatePdf($html, $fileFolder, $fileName) {
    ob_start();

    $programesetting = R::findOne('programesetting');

    require_once("../../_library/plugins/tcpdf/tcpdf.php");
// create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
    $pdf->SetMargins(5, $programesetting->above2, 5);
    $pdf->SetHeaderMargin(0);
    $pdf->SetFooterMargin(0);

    $pdf->SetPrintHeader(false);
    $pdf->SetPrintFooter(false);


// set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
    if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {
        require_once(dirname(__FILE__) . '/lang/eng.php');
        $pdf->setLanguageArray($l);
    }

// ---------------------------------------------------------
    define('K_PATH_FONTS', dirname(__FILE__) . '/../../_library/plugins/tcpdf/');
// set font
    $pdf->SetFont('dejavusans', '', 10);
// add a page
    $pdf->AddPage();



// output the HTML content
    $pdf->writeHTML($html, true, false, true, false, '');

// reset pointer to the last page
    $pdf->lastPage();

    if (!file_exists('../../upload/' . $fileFolder)) {
        //    print_r(555);
        mkdir('../../upload/' . $fileFolder, 0777, true);
    }

    if (file_exists('/../../upload/' . $fileFolder . '/' . $fileName . '.pdf')) {
        //echo $imageNewName;
        chmod('/../../upload/' . $fileFolder . '/' . $fileName . '.pdf', 0777);
        unlink('/../../upload/' . $fileFolder . '/' . $fileName . '.pdf');
    }
    $pdf->Output(__DIR__ . '/../../upload/' . $fileFolder . '/' . $fileName . '.pdf', 'F');

    //$res = sendPdf($fileName, $dataArray, $reDeliver);

    return 1;
//============================================================+
// END OF FILE
//============================================================+
}


function sendFileWithData($data, $url) {


  //  $apiKey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJuYXMtbGFiIiwiYXVkIjoibmFzLWxhYiIsImp0aSI6ImZLb2tpeEw5UloiLCJpYXQiOjE3MDU2NTc5MjAuMjEzNjk1fQ.9N4Vi0cq5JFM4maBEKPCtElbLEtk3CHXQZJDtm1xECM';
    $apiKey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJuYXMtbGFiIiwiYXVkIjoibmFzLWxhYiIsImp0aSI6IlhhUG5jWk9NNUciLCJpYXQiOjE3MTcwODE1NjMuNzUyODkxfQ.afHJiQtwldT_nNjUrt_WESapqCl5YyOWl_vUEHTJchI';

    // print_r($dataArray['patient_id']);
    // Initializes a new cURL session
    $curl = curl_init($url);
//    print_r($curl);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    // 1. Set the CURLOPT_RETURNTRANSFER option to true
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// 2. Set the CURLOPT_POST option to true for POST request
    curl_setopt($curl, CURLOPT_POST, true);
// 3. Set the request data 
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// 4. Set  headers for API Auth 

    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
//        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
        'AuthorizationKey: Bearer ' . $apiKey
    ));

    // Execute cURL request with all previous settings
    $response = curl_exec($curl);

    if (curl_errno($curl)) {
        $error_msg = curl_error($curl);
    }
//    print_r($error_msg);
    // Close cURL session
    curl_close($curl);

//    echo $response . PHP_EOL;

    $res = json_decode($response);


    if ($res->success) {
        return $res->success;
    } else {
        return $res->error->message;
    }


    return $link;
}