<?php 
if(file_exists('../../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../../'.$_REQUEST['tenant'].'/config.php'); }
if(file_exists('/config.php')){require_once('/config.php'); }

    switch ($_REQUEST['FUNCTION']){
        default:break;


   case "revoke":

            $stmt = mysqli_query($GLOBALS['con'],"SELECT * FROM `renewals` WHERE `id`='".$_REQUEST['id']."'")or die(mysqli_error($GLOBALS['con']));
            $iv=mysqli_fetch_array($stmt);
            $file='../../../../'.$_REQUEST['tenant'].'/renewals/'.$iv['invoiceName'];
           
            unlink($file);
          
          
            $stmt = mysqli_query($GLOBALS['con'],"DELETE FROM `renewals` WHERE `id`='".$_REQUEST['id']."'")or die(mysqli_error($GLOBALS['con']));
            $stmt = mysqli_query($GLOBALS['con'],"DELETE FROM `invoices_temp` WHERE `invNo`='".$_REQUEST['id']."'")or die(mysqli_error($GLOBALS['con']));
            
    break;

    case "setLapse":
        $stmt = $GLOBALS['con']->prepare("UPDATE `clientdetails` SET `renewal_status`='LAPSED' WHERE `clientnumber`='".$_REQUEST['clientnumber']."'")or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();$iv=$stmt->get_result();$stmt->close();	
        echo "success";
    break;

    case "setJustRenewed";
        $sql=mysqli_query($GLOBALS['con'],"SELECT * FROM `renewals` WHERE `id`='".$_REQUEST['id']."'");
        $d=mysqli_fetch_array($sql);
        $recall=mysqli_query($GLOBALS['con'],"SELECT * FROM `invoices_temp` WHERE `invNo`='".$d['renewalnumber']."'");
        $recallData=mysqli_fetch_array($recall);


        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `clientnumber`=?")or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i',$recallData['client']);$stmt->execute();$iv=$stmt->get_result();$stmt->close();
        $cd=mysqli_fetch_array($iv);
        
        $form_date = $_REQUEST['date']; 
        $term_years = $cd['term_years'];  
        $form_date_obj = DateTime::createFromFormat('d-m-Y', $form_date);
        $interval_string = "P";
        if ($term_years >= 1) {
            $interval_string .= intval($term_years) . "Y"; 
        }
        if ($term_years - intval($term_years) == 0.5) {
            $interval_string .= "6M"; 
        }
        $interval = new DateInterval($interval_string);
        $new_renewal_date_obj = $form_date_obj->add($interval);
        $new_renewal_date = $new_renewal_date_obj->format("d-m-Y");      
        $futureDate = $new_renewal_date;


        $stmt = $GLOBALS['con']->prepare("UPDATE `clientdetails` SET `renewal_status`='ACTIVE', `renewal_date`='".strtotime($futureDate)."' WHERE `clientnumber`='".$recallData['client']."'")or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();$stmt->close();

        if($recallData['target']=="client"){                
            $clientName=str_replace('&','',$cd['clientname']);
            $billingName=str_replace('&','',$cd['billing_name']);
            $emailString=$recallData['client'].'|'.$billingName.'|'.$cd['billing_email'].'|'.$clientName.' Invoice |Your Renewal|||||renewalConfirm|';
        }

        if($recallData['target']=="broker"){
            $clientName=str_replace('&','',$cd['clientname']);
            $billingName=str_replace('&','',$ad['billing_name']);
            $stmt2 = $GLOBALS['con']->prepare("SELECT * FROM `brokers` WHERE `broker_number`=?")or die(mysqli_error($GLOBALS['con']));
            $stmt2->bind_param('i',$cd['broker_number']);$stmt2->execute();$avy=$stmt2->get_result();$stmt2->close();
            $ad=mysqli_fetch_array($avy);
            $emailString=$recallData['client'].'|'.$billingName.'|'.$ad['billing_email'].'|'.$clientName.' Invoice |Your Renewal|||'.$ad['email'].'| |renewalConfirm|';
        }

        if($recallData['target']=="agent"){
            $clientName=str_replace('&','',$cd['clientname']);
            $billingName=str_replace('&','',$ad['billing_name']);
            $stmt2 = $GLOBALS['con']->prepare("SELECT * FROM `agents` WHERE `agent_number`=?")or die(mysqli_error($GLOBALS['con']));
            $stmt2->bind_param('i',$cd['agent_number']);$stmt2->execute();$avs=$stmt2->get_result();$stmt2->close();
            $ad=mysqli_fetch_array($avs);
            $emailString=$recallData['client'].'|'.$billingName.'|'.$ad['billing_email'].'|'.$clientName.' Invoice |Your Renewal|||'.$ad['email'].'||renewalConfirm|';
        }

        
        $dataArray=array(
            "client"=>$recallData['client'],
            "invoice"=>$invoiceId,
            "renewal"=>$d['renewalnumber'],
            "date"=>$recallData['date'],
            "target"=>$recallData['target'],
            "email"=>$emailString
        );
        $update=mysqli_query($GLOBALS['con'],"UPDATE `invoices_temp` SET `status`='8' WHERE `invNo`='".$d['renewalnumber']."'");

        $stmt = $GLOBALS['con']->prepare("UPDATE `clientdetails` SET `renewal_status`='ACTIVE', `renewal_date`='".strtotime($futureDate)."' WHERE `clientnumber`='".$d['clientnumber']."'")or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();$stmt->close();

        $stmt = $GLOBALS['con']->prepare("DELETE FROM `renewals` WHERE `id`='".$_REQUEST['id']."'")or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();$stmt->close(); 
        $return=json_encode($dataArray);
        echo $return;
    break;
    

    case "setRenewed":
        $sql=mysqli_query($GLOBALS['con'],"SELECT * FROM `renewals` WHERE `id`='".$_REQUEST['id']."'");
        $d=mysqli_fetch_array($sql);
        
        $recall=mysqli_query($GLOBALS['con'],"SELECT * FROM `invoices_temp` WHERE `invNo`='".$d['renewalnumber']."'");
        $recallData=mysqli_fetch_array($recall);
        $curDate=date('d-m-Y');
        $nextDate=date('d-m-Y', strtotime('+30 days', strtotime(date('d-m-Y'))));
                
        $stmt = $GLOBALS['con']->prepare("INSERT INTO `invoices` VALUES(
            NULL,
            '".$recallData['client']."',
            '".$recallData['agent']."',
            '".$recallData['broker']."',
            '".$recallData['address']."',
            '".$recallData['items']."',
            '".$recallData['totals']."',
            '".$recallData['notes']."',
            '0.2',
            '".strtotime($curDate)."',
            '".strtotime($nextDate)."',
            '".$recallData['date_paid']."',
            '".$recallData['sent']."',
            '1',
            '".$recallData['payment_type']."',
            '".$recallData['chequeNo']."',
            '".$recallData['commission']."',
            '".$recallData['commission_paid']."',
            '".$recallData['filter']."',
            '".$recallData['target']."',
            '".$_REQUEST['purchaseOrder']."'
            )")or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();$iv=$stmt->get_result();$stmt->close();
        $invoiceId=mysqli_insert_id($GLOBALS['con']);
        $remove=mysqli_query($GLOBALS['con'],"DELETE FROM `invoices_temp` WHERE `invNo`='".$d['renewalnumber']."'");
        
        $address = unserialize($recallData['address']);
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `clientnumber`=?")or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i',$recallData['client']);$stmt->execute();$iv=$stmt->get_result();$stmt->close();
        $cd=mysqli_fetch_array($iv);

        $form_date = $_REQUEST['date']; 
        $term_years = $cd['term_years']; 
        $form_date_obj = DateTime::createFromFormat('d-m-Y', $form_date);
        $interval_string = 'P';
        if ($term_years >= 1) {
            $interval_string .= intval($term_years) . 'Y';
        }
        if ($term_years - intval($term_years) == 0.5) {
            $interval_string .= '6M';
        }

        // if we never added any Y or M, fall back to days = 0
        if ($interval_string === 'P') {
            $interval_string .= '0D';
        }

        $interval = new DateInterval($interval_string);
        $new_renewal_date_obj = $form_date_obj->add($interval);
        $new_renewal_date = $new_renewal_date_obj->format("d-m-Y");      
        $futureDate = $new_renewal_date;
        
        if($recallData['target']=="client"){                
            $clientName=str_replace('&','',$cd['clientname']);
            $billingName=str_replace('&','',$cd['billing_name']);             
            $billingEmail=$cd['billing_email'];
            $emailSubject=$clientName.' Invoice';
            $emailMessage='Your invoice number '.$invoiceId;
            $emailFile=$invoiceId.'_invoice.pdf';
            $emailInvoice=$invoiceId;
            $emailFunction='renewalInvoice';
        }

        if($recallData['target']=="broker"){
            $stmt2 = $GLOBALS['con']->prepare("SELECT * FROM `brokers` WHERE `broker_number`=?")or die(mysqli_error($GLOBALS['con']));
            $stmt2->bind_param('i',$cd['broker_number']);$stmt2->execute();$avy=$stmt2->get_result();$stmt2->close();
            $ad=mysqli_fetch_array($avy);
            $clientName=str_replace('&','',$cd['clientname']);
            $billingName=str_replace('&','',$cd['billing_name']);             
            $billingEmail=$ad['billing_email'];
            $emailSubject=$clientName.' Invoice';
            $emailMessage='Your invoice number '.$invoiceId;
            $emailFile=$invoiceId.'_broker.pdf';
            $emailInvoice=$invoiceId;
            $emailFunction='renewalInvoice';
            $email=$ad['email'];
        }

        if($recallData['target']=="agent"){
            $stmt2 = $GLOBALS['con']->prepare("SELECT * FROM `agents` WHERE `agent_number`=?")or die(mysqli_error($GLOBALS['con']));
            $stmt2->bind_param('i',$cd['agent_number']);$stmt2->execute();$avs=$stmt2->get_result();$stmt2->close();
            $ad=mysqli_fetch_array($avs);
            $clientName=str_replace('&','',$cd['clientname']);
            $billingName=str_replace('&','',$cd['billing_name']);             
            $billingEmail=$ad['billing_email'];
            $emailSubject=$clientName.' Invoice';
            $emailMessage='Your invoice number '.$invoiceId;
            $emailFile=$invoiceId.'_agent.pdf';
            $emailInvoice=$invoiceId;
            $emailFunction='renewalInvoice';
            $email=$ad['email'];
        }

        $stmt = $GLOBALS['con']->prepare("UPDATE `clientdetails` SET `renewal_status`='ACTIVE', `renewal_date`='".strtotime($futureDate)."' WHERE `clientnumber`='".$d['clientnumber']."'")or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();$stmt->close();

        $dataArray=array(
            "client"=>$recallData['client'],
             "clientName"=>$clientName,
            "invoice"=>$invoiceId,
            "renewal"=>$d['renewalnumber'],
            "date"=>$recallData['date'],
            "target"=>$recallData['target'],
            "billingName"=> $billingName,
            "billingEmail"=> $billingEmail,
            "email"=> $email,
            "emailSubject"=>$emailSubject,
            "emailMessage"=>$emailMessage,
            "emailFolder"=>'invoices',
            "emailFile"=>$emailFile,
            "emailInvoice"=>$emailInvoice,
            "emailFunction"=>$emailFunction

        );
        $stmt = $GLOBALS['con']->prepare("DELETE FROM `renewals` WHERE `id`='".$_REQUEST['id']."'")or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();$stmt->close(); 
        $return=json_encode($dataArray);
        echo $return;
    break;

   }
   
   ?>