<?php
require('config.php');
require("vendor/phpmailer/phpmailer/class.phpmailer.php");
require("vendor/phpmailer/phpmailer/class.smtp.php");
$datetotransfer = $_POST['datetotransfer']; 
$endtransferdate = $_POST['endtransferdate']; 
$service = $_POST['service'];
$emailheader = $_POST['emailheader'];
$emaildesc = $_POST['emaildesc'];

$linkID = new PDO('mysql:host='.Config::DB_HOST.';dbname='.Config::DB_NAME, Config::DB_USERNAME, Config::DB_PASSWORD);
$linkID->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Setting ERRMODE
$company_name = $linkID->query("SELECT * FROM ea_settings WHERE ea_settings.id=14")->fetchAll(PDO::FETCH_ASSOC);
$company_email = $linkID->query("SELECT * FROM ea_settings WHERE ea_settings.id=15")->fetchAll(PDO::FETCH_ASSOC);
$company_link = $linkID->query("SELECT * FROM ea_settings WHERE ea_settings.id=16")->fetchAll(PDO::FETCH_ASSOC);

$result =  $linkID->query("SELECT CONCAT(DAYNAME(start_datetime),' ',MONTHNAME(start_datetime),' ', DAY(start_datetime)) as concatday,
    TIME(start_datetime) as time,
    CONCAT(DAYNAME(end_datetime),' ',MONTHNAME(end_datetime),' ', DAY(end_datetime)) as concatendday,
    TIME(end_datetime) as endtime,
    CONCAT(DAYNAME(book_datetime),' ',MONTHNAME(book_datetime),' ', DAY(book_datetime)) as concatbookday,
    TIME(end_datetime) as booktime,
    YEAR(start_datetime) as year, 
    MONTH(start_datetime) as monthnumber, 
    MONTHNAME(start_datetime) as monthday, 
    DAY(start_datetime) as daynumber, 
    DAYNAME(start_datetime) as dayname, 
    HOUR(start_datetime) as hour, 
    MINUTE(start_datetime) as minute, 
   COUNT(*) as countbookdate, 
    sum(ea_services.price) as totalprice, 
    ea_appointments.book_datetime, 
    ea_appointments.id_users_provider, 
      ea_appointments.id_company, company.name as companyname, 
    ea_appointments.start_datetime, ea_appointments.end_datetime, 
    ea_users.notes as usernotes, 
    ea_appointments.notes as apptnotes, 
        ea_appointments.hash as hash, 
    ea_appointments.id as apptid,
      ea_appointments.formid as apptformid,
    ea_services.name as servicename, 
    ea_users.first_name as firstname, 
    ea_users.last_name as lastname,
    ea_users.email as emailperson, 
  ea_services.name as servicename, 
  ea_services.duration as serviceduration, 
    ea_users.phone_number as phoneperson FROM `ea_appointments`
    inner JOIN 
        ea_services 
        on 
        ea_appointments.id_services=ea_services.id 
        
            inner JOIN 
        company 
        on 
        ea_appointments.id_company=company.id
            
    join 
        ea_users 
        on 
        ea_appointments.id_users_customer=ea_users.id 
     WHERE is_unavailable=0 AND id_services=".$service. " AND ea_appointments.start_datetime BETWEEN ".'"'.$datetotransfer.' '.'00:00:00'.'"'." AND ".'"'.$datetotransfer.' '.'23:59:59'.'"'.' '."GROUP BY YEAR(start_datetime), MONTH(start_datetime), MONTHNAME(start_datetime), DAY(start_datetime), DAYNAME(start_datetime), concatday, time, HOUR(start_datetime), MINUTE(book_datetime), ea_services.name, ea_appointments.book_datetime,ea_appointments.start_datetime,ea_appointments.end_datetime, ea_users.first_name, ea_users.last_name, ea_appointments.id, ea_users.email, ea_users.phone_number, ea_users.notes, ea_appointments.notes
     ORDER BY YEAR(start_datetime), MONTH(start_datetime), MONTHNAME(start_datetime), DAY(start_datetime), DAYNAME(start_datetime), HOUR(start_datetime), MINUTE(book_datetime), ea_users.last_name, ea_users.first_name")->fetchAll(PDO::FETCH_ASSOC);

$location =  $linkID->query("select ea_users.first_name as locationname from ea_services_providers inner join ea_users on ea_services_providers.id_users=ea_users.id where ea_services_providers.id_services=".$service)->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $r) {
    try{
        $companylinke = $linkID->query("SELECT * FROM company WHERE id=".$r['id_company'])->fetchAll(PDO::FETCH_ASSOC);

    $br1start = str_replace($datetotransfer, $endtransferdate, $r['start_datetime']);
    $br1end = str_replace($datetotransfer, $endtransferdate, $r['end_datetime']);

    $data = [
        'id' => $r['apptid'],
        'start' => $br1start,
        'end' => $br1end,
    ];

    $sql = "UPDATE ea_appointments SET start_datetime=:start, end_datetime=:end where id=:id";
    $stmt = $linkID->prepare($sql);
    $stmt->execute($data);

        $target_url = Config::xml_server_url_secure . '/' . 'amjaygetforms';
        $post = array();
        $post['nurseid'] = 6;
        $post['nursepw'] = 'Taals123';
        $post['username'] = 'MM2020';
        $post['action']='updateappointment';

        $post['formid']=$r['apptformid'];
        $post['appointmentdate']=$r['start_datetime'];


        $he = 'X-erefill-args: scode=' . Config::scode;
        $header = array($he);


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_VERBOSE, 0);
        curl_setopt($ch, CURLOPT_URL, $target_url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);


        $result = curl_exec($ch);

        $pos = strpos($result, 'xml');

        if ($pos !== false) {
            $xmlbro = simplexml_load_string($result) or die("Error: Cannot create object");

        } else {
            throw new Exception('Error Submitting 1');

        }

        if (!empty($xmlbro->form[0]->row[0]->attributes()[0])) {
        } else {
            throw new Exception('Error Submitting 2');
        }
}catch(Exception $e) {
  echo 'Message: Following appointment id failed to transfer'.$r['apptid']  .$e->getMessage();
}
try{
    if ($r['emailperson'] !== '') {
        $mail = new \PHPMailer;
        $mail->IsSMTP(); // enable SMTP
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
        $mail->SMTPDebug = 0;
        $mail->SMTPAuth = TRUE;
        $mail->SMTPSecure = 'tls'; // tls or ssl
        //$mail->Port     = "587";
        $mail->Username = Config::EMAIL;
        $mail->Password = Config::EMAIL_PASSWORD;
       // $mail->Host     = "myappts.org";
        $mail->Mailer   = "smtp";
        $mail->SetFrom(Config::EMAIL, $company_name[0]['value']);
        $mail->AddAddress($r['emailperson']);
        $mail->Subject = $emailheader;
        $html = file_get_contents('transferapptsemail.php');
        $tobereplaced = array("companylinkbro", "companynamebro", "servicenamebro", "emaildescriptionbro", "firstnamebro", "lastnamebro", "emailpersonbro", "phonepersonbro", "frontendcolor", "servicename", "serviceduration", "startdatenewappt", "enddatenewappt", "apptlinkbro", "locationname", "companyname");
        $replacements = array($company_link[0]['value'], $company_name[0]['value'], $r['servicename'], $emaildesc, $r['firstname'], $r['lastname'], $r['emailperson'], $r['phoneperson'], Config::FRONTEND_COLOR, $r['servicename'], $r['serviceduration'], $br1start, $br1end, Config::BASE_URL.'/index.php/appointments/index/'.$r['hash'].'?company='.$companylinke[0]['hash_id'], $location[0]['locationname'], $r['companyname']);
        $htmlone = str_replace($tobereplaced, $replacements, $html);
        $mail->MsgHTML($htmlone);
        $mail->IsHTML(true);

        if (!$mail->Send()) {
            echo "Mailer Error: " . $mail->ErrorInfo;
        } else {

            $current_date = new DateTime();
            $today = date("Y-m-d H:i:s", $current_date->getTimestamp());
            //echo $today;
            $dataone = [
                'datesent' => $today,
                'pharmacy' => Config::COMPANY_FIRST_NAME . ' ' . Config::COMPANY_LAST_NAME,
                'apptid' => $r['apptid'],
            ];
            $sqlone = "INSERT INTO `emails_sent`(`date_sent`, `pharmacy`, `apptid`, `reason`) VALUES (:datesent, :pharmacy, :apptid, 'transfer appts')";
            //echo 'done2';
            $stmtone = $linkID->prepare($sqlone);
            $stmtone->execute($dataone);
            $mail->ClearAddresses();
            $mail->ClearAllRecipients();
            
        }
    }
}catch(Exception $e) {
  echo 'Message: Following appointment id failed to send email'.$r['apptid']  .$e->getMessage();
}

}

echo 'Process was completed'; 

?>