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


switch ($_REQUEST['FUNCTION']){
default:break;
case "detectPWS":
    function getPssrNo($itemnumber){
        //check for instance
        $stmt = $GLOBALS['con']->prepare("SELECT `wsnumber` FROM `wsitems` WHERE `itemnumber`=?")or die($error=mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i',$itemnumber);$stmt->execute();$res=$stmt->get_result();$stmt->close();
        $d=mysqli_fetch_array($res);
           
        if(empty($d['wsnumber'])){return 'None found';}
        else{return $d['wsnumber'];}
    }
     $files = delivery_report_list_tokens($_REQUEST['items'] ?? '');
     $jsonMode = (($_REQUEST['format'] ?? '') === 'json');
     $found = [];
     $warnings = [];
     $seen = [];
     $ret = '';
     $c=1;
    foreach($files as $file){
        $item = delivery_report_token_parts($file); 
        if ($item['itemnumber'] === '') { continue; }
            $pssr=getPssrNo($item['itemnumber']);
    if($pssr=="None found"){}
    else{
      $wsFile = 'WS'.preg_replace('/[^A-Za-z0-9_-]/', '', (string)$pssr).'.pdf';
      if(isset($seen[$wsFile])){ continue; }
      $seen[$wsFile] = true;
      if(file_exists('../../../'.TENANT_URL.'/output/wsfiles/'.$_REQUEST['client'].'/'.$wsFile)){  
    $ret.= str_replace('.pdf', '', $wsFile).'|';
    $found[] = str_replace('.pdf', '', $wsFile);
    $c++;
      } else {
    $warnings[] = 'Written Scheme '.$wsFile.' is linked to an item, but the file has not been created yet and was not attached.';
      }
    }
}
    if ($jsonMode) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['files' => array_values(array_unique($found)), 'warnings' => array_values(array_unique($warnings))], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        break;
    }
    echo $ret;
    
    
break;

case "detectWS":
    function getPssrNo($itemnumber){
        //check for instance
        $stmt = $GLOBALS['con']->prepare("SELECT `wsnumber` FROM `wsitems` WHERE `itemnumber`=?")or die($error=mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i',$itemnumber);$stmt->execute();$res=$stmt->get_result();$stmt->close();
        $d=mysqli_fetch_array($res);
           
        if(empty($d['wsnumber'])){return 'None found';}
        else{return $d['wsnumber'];}
    }
     $files= json_decode($_REQUEST['items'], true ); 
     $c=1;
    foreach($files as $file){
        $client=$file['source'];
        $item=$file['file'];
        $item=str_replace('.pdf','', $item);
        $item=explode('_', $item);
        $client=explode('/', $client);
        $pssr=getPssrNo($item[1]);
    if($pssr=="None found"){}
    else{
      if(file_exists('../../output/wsfiles/'.$client[2].'/WS'.$pssr.'.pdf')){  
    $ret.= '<div id="wsContainer_'.$c.'" class="col-1 mb-3 text-center rounded"><i class="fad fa-file-word fa-2x" style="--fa-primary-color: black; --fa-secondary-color: white; filter: drop-shadow(0 0 2px #000)" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"  data-html="true" title="WS'.$pssr.'.pdf"></i>
    <input type="hidden" class="form-control-sm filename is-valid" name="wsreport_'.$c.'" id="ws_1" value="WS'.$pssr.'.pdf" readonly>
    <input type="hidden" name="wssource_'.$c.'" id="wssource_'.$c.'" value="output/wsfiles/'.$client[2].'" readonly><i class="fad fa-window-close" style="cursor:pointer; --fa-primary-color: red;" onclick="wsDelete(\''.$c.'\')"></i></div>';
    $c++;
      }
    }
}
    echo ($ret);
    
    
break;     

case "detectZWS":

  //check for instance
  $stmt = $GLOBALS['con']->prepare("SELECT `wsnumber` FROM `wsitems` WHERE `itemnumber`=?")or die($error=mysqli_error($GLOBALS['con']));
  $stmt->bind_param('i',$itemnumber);$stmt->execute();$res=$stmt->get_result();$stmt->close();
  $d=mysqli_fetch_array($res);
     
  if(empty($d['wsnumber'])){echo 0;}
  else{echo $d['wsnumber'];}

break;  

case "setDelivered":

if($_REQUEST['mode']=="multi"){
$items = delivery_report_list_tokens($_REQUEST['string'] ?? '');
$now=strtotime('now');
foreach($items as $item){
$item = delivery_report_token_parts($item);
if ($item['repnumber'] === '') { continue; }
$stmt = $GLOBALS['con']->prepare("UPDATE `reportitems` SET `delivery`='".$now."' WHERE `repnumber`='".$item['repnumber']."' ")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$cc=$stmt->get_result();$stmt->close();
}
}
else{
$items = delivery_report_list_tokens($_REQUEST['string'] ?? '');
$now=strtotime('now');
foreach($items as $item){
$item = delivery_report_token_parts($item);
if ($item['repnumber'] === '') { continue; }
$stmt = $GLOBALS['con']->prepare("UPDATE `reportitems` SET `delivery`='".$now."' WHERE `repnumber`='".$item['repnumber']."' ")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$cc=$stmt->get_result();$stmt->close();

}
}
break;

case "getAsssets":
$stmt = $GLOBALS['con']->prepare("SELECT `itemnumber`,`desc`,`plantnumber`,`serialnumber`,`manf`,`model`,`duedate` FROM `itemdetails` WHERE `statuslive`='1' AND `clientnumber`='".$_REQUEST['clientnumber']."'")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$cc=$stmt->get_result();$stmt->close();

$ret='<table id="schedule" class="table table-small table-striped">
<thead>
<tr><th>Item No</th><th>Description</th><th>Plant Number</th><th>Serial Number</th><th>Manufacturer</th><th>Model</th><th>Due Date</th></tr>
</thead>
<tbody>';
while($pd=mysqli_fetch_array($cc)){
if($pd['duedate']==""){$date="None on record";}
else{$date=date('d-m-Y',$pd['duedate']);}
$ret.='<tr><td>'.$pd['itemnumber'].'</td><td>'.$pd['desc'].'</td><td>'.$pd['plantnumber'].'</td><td>'.$pd['serialnumber'].'</td><td>'.$pd['manf'].'</td><td>'.$pd['model'].'</td><td>'.$date.'</td></tr>';
}
$ret.='</tbody></table>';
echo $ret;
break;
	
}



function listClient($c, $n, $t){
switch($t){
default:break;

case "code":
$stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname` FROM `clientdetails` WHERE `statuslive`='1' ORDER BY `clientname` ASC")or die(mysqli_error("listClient A: ".$GLOBALS['con']));
$stmt->execute();$cc=$stmt->get_result();$stmt->close();	
while($pd=mysqli_fetch_array($cc)){$ca[]=$pd;}

$ret='<select class="form-control form-control-sm" id="'.$n.'" name="'.$n.'">'; 
foreach($ca as $px){
if($c==$px['code']){$s="SELECTED";}else{$s="";}
$ret.='<option value="'.$px['clientnumber'].'" '.$s.'>'.$px['clientname'].'</option>';//.PHP_EOL;
}
$ret.='</select>';
return($ret.$error);
break;

case "name":
$stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname` FROM `clientdetails` WHERE `statuslive`='1'  ORDER BY `clientname` ASC")or die(mysqli_error("listClient B: ".$GLOBALS['con']));
$stmt->execute();$cc=$stmt->get_result();$stmt->close();	
while($pd=mysqli_fetch_array($cc)){$ca[]=$pd;}

$ret='<select class="form-control form-control-sm autocomplete" id="'.$n.'" name="'.$n.'">'; 
foreach($ca as $px){
if($c==$px['code']){$s="SELECTED";}else{$s="";}
$ret.='<option value="'.$px['clientname'].'" '.$s.'>'.$px['clientname'].'</option>';//.PHP_EOL;
}
$ret.='</select>';
return($ret.$error);
break;

case "select":
$stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname` FROM `clientdetails` WHERE `statuslive`='1'  ORDER BY `clientname` ASC")or die(mysqli_error("listClient B: ".$GLOBALS['con']));
$stmt->execute();$cc=$stmt->get_result();$stmt->close();	

$ret='<select class="form-control form-control-sm autocomplete" id="'.$n.'" name="'.$n.'">'; 
while($pd=mysqli_fetch_array($cc)){
$ret.='<option value="'.$pd['clientnumber'].'" '.$s.'>'.$pd['clientname'].'</option>';//.PHP_EOL;
}
$ret.='</select>';
return($ret.$error);
break;

case "ajax":
$stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname` FROM `clientdetails` WHERE `statuslive`='1'  ORDER BY `clientname` ASC")or die(mysqli_error("listClient C: ".$GLOBALS['con']));
$stmt->execute();$cc=$stmt->get_result();$stmt->close();	
$cnt=mysqli_num_rows($cc);
while($pd=mysqli_fetch_array($cc)){$ca[]=$pd;}
$co=0;
$ret='var clientList = ['; 
foreach($ca as $px){
$px['clientname']=str_replace('"','',$px['clientname']);
$px['clientname']=str_replace('\&','and',$px['clientname']);
$co++;
if($co==$cnt){$s="";}else{$s=",";}
$ret.='{"value":"'.$px['clientname'].'","name":"'.$px['clientnumber'].'"}'.$s.PHP_EOL;

}
$ret.='];';
return($ret.$error);
break;
		
}	
}

function getItemName($itemnumber){
$stmt = $GLOBALS['con']->prepare("SELECT `desc` FROM `itemdetails` WHERE `itemnumber`=?")or die(mysqli_error("getItemName: ".$GLOBALS['con']));
$stmt->bind_param('i',$itemnumber);$stmt->execute();$rc=$stmt->get_result();$stmt->close();	
$cd=mysqli_fetch_array($rc);	
return $cd['desc'];
}



?>
