<?php //ini_set('display_errors', 1);ini_set('display_startup_errors', 1);error_reporting(E_ALL);
if(file_exists('../../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../../'.$_REQUEST['tenant'].'/config.php'); }
if(file_exists('/config.php')){require_once('/config.php'); }


function genInvoice($client,$mode){
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `clientnumber`=?")or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i',$client);$stmt->execute();$ccall=$stmt->get_result();$stmt->close();
    $cd=mysqli_fetch_array($ccall);
    $agentID='';
    $brokerID='';
$itemArray = [
    [
        'service'  => "Contract Renewal",
        'notes'    => "Renewal of " . $cd['clientname'] . ", contract number " . $cd['contract_number'],
        'rate'     => $cd['rate_per_hour'],
        'quantity' => "1"
    ]
];

$json = json_encode($itemArray, JSON_UNESCAPED_SLASHES);
$serialized = serialize($json);


$_REQUEST['items'] = $serialized;
    
        if ($mode === "broker") {
            $stmt2 = $GLOBALS['con']->prepare("SELECT * FROM `brokers` WHERE `broker_number` = ?");
            if (!$stmt2) {
                die("Prepare failed: " . $GLOBALS['con']->error);
            }

            $stmt2->bind_param('i', $cd['broker_number']);
            $stmt2->execute();
            $avy = $stmt2->get_result();
            $ad = $avy->fetch_assoc();
            $stmt2->close();

            $ratePerHour = floatval(str_replace(',', '', $cd['rate_per_hour']));
            $vatRate     = floatval(str_replace(',', '', getCompanyDetails('vatrate')));
            $commission  = floatval(str_replace(',', '', $cd['commission']));

            $_REQUEST['sumTotal']   = $ratePerHour;
            $_REQUEST['vatTotal']   = $ratePerHour * $vatRate;
            $_REQUEST['vatrate']    = $vatRate;
            $_REQUEST['filter']     = "Contract Renewal";
            $_REQUEST['target']     = "broker";
            $noticeEmail            = $cd['billing_email'];
            $brokerID               = $cd['broker_number'];

            $_REQUEST['comTotal'] = $cd['comType'] == 0
                ? $ratePerHour * ($commission / 100)
                : $commission;

            $address = array_map(
                fn($val) => is_string($val) ? htmlspecialchars($val, ENT_QUOTES, 'UTF-8') : $val,
                [
                    'client_name'      => $client,
                    'billing_name'     => $ad['billing_name'],
                    'billing1'         => $ad['billing1'],
                    'billing2'         => $ad['billing2'],
                    'billing_town'     => $ad['billing_town'],
                    'billing_county'   => $ad['billing_county'],
                    'billing_postcode' => $ad['billing_postcode'],
                    'email'            => $ad['billing_email'],
                    'contract_number'  => $cd['contract_number'],
                    'broker_number'    => $cd['broker_number'],
                    'broker_name'      => $ad['broker_name'],
                    'commission'       => number_format($_REQUEST['comTotal'], 2),
                ]
            );
        }

        if ($mode === "agent") {
        $stmt2 = $GLOBALS['con']->prepare("SELECT * FROM `agents` WHERE `agent_number` = ?");
        if (!$stmt2) {
            die("Prepare failed: " . $GLOBALS['con']->error);
        }

        $stmt2->bind_param('i', $cd['agent_number']);
        $stmt2->execute();
        $avs = $stmt2->get_result();
        $ad  = $avs->fetch_assoc();
        $stmt2->close();

        $ratePerHour = floatval(str_replace(',', '', $cd['rate_per_hour']));
        $vatRate     = floatval(str_replace(',', '', getCompanyDetails('vatrate')));
        $commission  = floatval(str_replace(',', '', $cd['commission']));

        $_REQUEST['sumTotal']   = $ratePerHour;
        $_REQUEST['vatTotal']   = $ratePerHour * $vatRate;
        $_REQUEST['vatrate']    = $vatRate;
        $_REQUEST['filter']     = "Contract Renewal";
        $_REQUEST['target']     = "agent";
        $agentID                = $cd['agent_number'];

        $_REQUEST['comTotal'] = $cd['comType'] == 0
            ? $ratePerHour * ($commission / 100)
            : $commission;

        $address = array_map(
            fn($val) => is_string($val) ? htmlspecialchars($val, ENT_QUOTES, 'UTF-8') : $val,
            [
                'client_name'      => $client,
                'billing_name'     => $ad['billing_name'],
                'billing1'         => $ad['billing1'],
                'billing2'         => $ad['billing2'],
                'billing_town'     => $ad['billing_town'],
                'billing_county'   => $ad['billing_county'],
                'billing_postcode' => $ad['billing_postcode'],
                'email'            => $ad['billing_email'],
                'contract_number'  => $cd['contract_number'],
                'agent_number'     => $cd['agent_number'],
                'agent_name'       => $ad['agent_name'],
                'commission'       => number_format($_REQUEST['comTotal'], 2),
            ]
        );
    }


    if ($mode === "client") {

    $ratePerHour = floatval(str_replace(',', '', $cd['rate_per_hour']));
    $vatRate     = floatval(str_replace(',', '', getCompanyDetails('vatrate')));
    $commission  = floatval(str_replace(',', '', $cd['commission']));

    $_REQUEST['sumTotal']   = $ratePerHour;
    $_REQUEST['vatTotal']   = $ratePerHour * $vatRate;
    $_REQUEST['vatrate']    = $vatRate;
    $_REQUEST['filter']     = "Contract Renewal";
    $_REQUEST['target']     = "client";

    $_REQUEST['comTotal'] = ($commission > 0)
        ? $ratePerHour * ($commission / 100)
        : 0;


    $address = array_map(
        fn($val) => is_string($val) ? htmlspecialchars($val, ENT_QUOTES, 'UTF-8') : $val,
        [
            'client_name'      => $client,
            'billing_name'     => $cd['billing_name'],
            'billing1'         => $cd['billing1'],
            'billing2'         => $cd['billing2'],
            'billing_town'     => $cd['billing_town'],
            'billing_county'   => $cd['billing_county'],
            'billing_postcode' => $cd['billing_postcode'],
            'email'            => $cd['billing_email'],
            'contract_number'  => $cd['contract_number'],
            'commission'       => number_format($_REQUEST['comTotal'], 2),
        ]
    );
}

    $_REQUEST['date']=date('d-m-Y');
    $_REQUEST['address']=serialize($address);
    $date=strtotime($_REQUEST['date']);
    $newDate = new DateTime($_REQUEST['date']);
    $newDate->add(new DateInterval('P30D'));
    $setDate=$newDate->format('d-m-Y');
    $dueDate=strtotime($setDate);
    
    //CLEANUP    
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `renewals` WHERE `clientnumber`='".$client."' AND `status`='0'")or die("2".mysqli_error($GLOBALS['con']));
    $stmt->execute();$iv=$stmt->get_result();$stmt->close();
    $renewalCount=mysqli_num_rows($iv);
    if($renewalCount>0){
    while($renewalData=mysqli_fetch_array($iv)){
        if(!empty($renewalData['invoiceName'])){
            unlink('../../'.$_REQUEST['tenant'].'/renewals/'.$renewalData['invoiceName']);
        }
    $stmt = $GLOBALS['con']->prepare("DELETE FROM `invoices_temp` WHERE `invNo`='".$renewalData['renewalnumber']."'")or die("2".mysqli_error($GLOBALS['con']));$stmt->execute();$stmt->close();
    $stmt = $GLOBALS['con']->prepare("DELETE FROM `renewals` WHERE `id`='".$renewalData['id']."'")or die("2".mysqli_error($GLOBALS['con']));$stmt->execute();$stmt->close();
    }}
    
    //CREATE NEW ENTRY
    $client     = !empty($client)   ? (int)$client   : null;
    $agentID    = !empty($agentID)  ? (int)$agentID  : null;
    $brokerID   = !empty($brokerID) ? (int)$brokerID : null;

    $address    = $_REQUEST['address'] ?? '';
    $items      = $_REQUEST['items'] ?? '';
    $totals     = ($_REQUEST['sumTotal'] ?? '0') . '|' . ($_REQUEST['vatTotal'] ?? '0');
    $vatrate    = $_REQUEST['vatrate'] ?? '0.2';
    $date       = (int)$date;
    $dueDate    = (int)$dueDate;
    $date_paid  = 0;
    $sent       = 0;
    $status     = 9;
    $payment_type = '';
    $chequeNo   = 0;
    $commission = $_REQUEST['comTotal'] ?? '0.00';
    $commission_paid = '0';
    $filter     = $_REQUEST['filter'] ?? '';
    $target     = $_REQUEST['target'] ?? '';
    $purchaseOrder= $_REQUEST['purchaseOrder'] ?? '';

    $sql = "INSERT INTO `invoices_temp`
    (`client`, `agent`, `broker`, `address`, `items`, `totals`, `vatrate`, 
    `date`, `date_due`, `date_paid`, `sent`, `status`, `payment_type`, 
    `chequeNo`, `commission`, `commission_paid`, `filter`, `target`, `purchase_order`)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $GLOBALS['con']->prepare($sql) or die("Prepare failed: " . mysqli_error($GLOBALS['con']));
    $stmt->bind_param(
        'iiissssiiiissssssss',
        $client,
        $agentID,
        $brokerID,
        $address,
        $items,
        $totals,
        $vatrate,
        $date,
        $dueDate,
        $date_paid,
        $sent,
        $status,
        $payment_type,
        $chequeNo,
        $commission,
        $commission_paid,
        $filter,
        $target,
        $purchaseOrder
    );

    if (!$stmt->execute()) {
        die("Insert failed: " . $stmt->error);
    }

    $renewalNumber = mysqli_insert_id($GLOBALS['con']);
    $stmt->close();


    $stmt = $GLOBALS['con']->prepare("INSERT INTO `renewals` VALUES(NULL,'".$client."','".$renewalNumber."','','".$date."','0')")or die("2".mysqli_error($GLOBALS['con']));
    $stmt->execute();$iv=$stmt->get_result();$stmt->close();
 $renewalEntry=mysqli_insert_id($GLOBALS['con']);
    
 return $renewalNumber;
}


$schedule='
<h2>Summary Schedule for: <strong>'. getClientName($_REQUEST['clientnumber']).'</strong></h2>
<table id="tableData" class="table table-sm table-striped">
     <thead class="p-0">
         <tr class="p-0"><th class="printhead py-0">Item</th><th class="printhead py-0">Count</th><th class="printhead py-0">Frequency</th></tr>
     </thead>
     <tbody>
     <tr><th>&nbsp;</th><td>&nbsp;</td><td>&nbsp;</td></tr>
';
  $unitsTotal=0;
  $sdcTotal=0;

 $sp=mysqli_query($GLOBALS['con'],"SELECT DISTINCT `desc`,`code` FROM `itemdetails` WHERE `clientnumber`='".$_REQUEST['clientnumber']."' AND `statuslive`='1'");
     while($sd=mysqli_fetch_array($sp)){

         $spc=mysqli_query($GLOBALS['con'],"SELECT `itemnumber` FROM `itemdetails` WHERE `clientnumber`='".$_REQUEST['clientnumber']."' AND `statuslive`='1'  AND `desc`='".$sd['desc']."'")or die(mysqli_error($GLOBALS['con']));
         $sdc=mysqli_num_rows($spc);

         $iuc=mysqli_query($GLOBALS['con'],"SELECT `units`,`frequency` FROM `dd_plant` WHERE `code`='".$sd['code']."'")or die(mysqli_error($GLOBALS['con']));
         $iuc=mysqli_fetch_array($iuc);

         $units=$iuc['units']*$sdc;
         $sdcTotal+=$sdc;
         $unitsTotal+=$units;
         $schedule.='<tr><th>'.$sd['desc'].'</th><td>'.$sdc.'</td><td>'.$iuc['frequency'].'</td></tr>';
     };
     $schedule.='
     <tr><th>&nbsp;</th><td>&nbsp;</td><td>&nbsp;</td></tr>
     </tbody>
    
     <tfoot class="bg-info text-white">
     <tr><th class="py-0">Total Items</th><td class="printhead py-0"><?= $sdcTotal?></td>
<td class="printhead py-0"></td>
</tr>
</tfoot>
</table>
';

switch($_REQUEST['mode']){
default:
echo 0;
break;

case "client":
echo genInvoice($_REQUEST['clientnumber'],$_REQUEST['mode']);
break;

case "agent":
echo genInvoice($_REQUEST['clientnumber'],$_REQUEST['mode']);
break;

case "broker":
echo genInvoice($_REQUEST['clientnumber'],$_REQUEST['mode']);
break;


}