<?php
  $page_title = 'Daily Plans';
  require_once('includes/load.php');
  // Checkin What level user has permission to view this page
 // page_require_level(1);
  
  $all_plans = find_all('plandetails');
  $all_articles = find_all('articledetails');
  $all_color = find_all('colordetails');
  $all_size = find_all('sizedetails');
  $all_stage = find_all('stagedetails');
  $fulldailyplan=join_dailyplan_table();
?>
<?php
 if(isset($_POST['add_pla'])){
   $req_field = array('dailyid','planid','jobno','StageId','CompletedQty','daydate','status');
   validate_fields($req_field);
   $pla_number = remove_junk($db->escape($_POST['planid']));
   $stagedet = remove_junk($db->escape($_POST['StageId']));
   $stageold = remove_junk($db->escape($_POST['OldStageId']));
   $TotalQty = remove_junk($db->escape($_POST['TotalQty']));
   $CompletedQty = remove_junk($db->escape($_POST['CompletedQty']));
   $CompletedDate = remove_junk($db->escape($_POST['daydate']));
   $jobno = remove_junk($db->escape($_POST['jobno']));
   $Vendor = remove_junk($db->escape($_POST['Vendor']));
   $Challan = remove_junk($db->escape($_POST['Challan']));
   $Remarks = remove_junk($db->escape($_POST['Remarks']));
   $Dailyplanid = remove_junk($db->escape($_POST['dailyid']));
   $status = remove_junk($db->escape($_POST['status']));
   //$daydate=date('Y-m-d',$daydate);

   $salesplandetials=find_by_id_custom("salesplandetails",$pla_number,'PlanId');
   $sapcode=$salesplandetials['SAPCode'];

   //$sizefull=find_by_id_custom("sizedetails",$artsize,'SizeId');
   $four=remove_junk($db->escape($_POST['four']));
   $five=remove_junk($db->escape($_POST['five']));
   $six=remove_junk($db->escape($_POST['six']));
   $seven=remove_junk($db->escape($_POST['seven']));
   $eight=remove_junk($db->escape($_POST['eight']));
   $nine=remove_junk($db->escape($_POST['nine']));
   $ten=remove_junk($db->escape($_POST['ten']));
   $eleven=remove_junk($db->escape($_POST['eleven']));
   $twelve=remove_junk($db->escape($_POST['twelve']));
   $thirteen=remove_junk($db->escape($_POST['thirteen']));
   $fourteen=remove_junk($db->escape($_POST['fourteen']));

   //print_r($currentplan);die();
   //$db= getDatabaseConnection();
  
   $userid = current_user();
     $p_userid = $userid['id'];
   if(empty($errors)){
   
    if($status !=0) {
      $sql  = "INSERT INTO trackingdetails (PlanId,DailyPlanId,JobNo,SAPCode,StageId,TotalQty,Quantity,CompletionDate,Remarks,VendorUnit,ChallanNo,Status,Four,Five,Six,Seven,Eight,Nine,Ten,Eleven,Twelve,Thirteen,Fourteen,UserId)";
      $sql .= " VALUES ({$pla_number},{$Dailyplanid},'{$jobno}','{$sapcode}',{$stagedet},{$TotalQty},{$CompletedQty},'{$CompletedDate}','{$Remarks}','{$Vendor}','{$Challan}',{$status},{$four},{$five},{$six},{$seven},{$eight},{$nine},{$ten},{$eleven},{$twelve},{$thirteen},{$fourteen},{$p_userid})";
      //echo $sql;die();
      if($db->query($sql)){
        $session->msg("s", "Successfully Added Plan Status");
        redirect('StatusTrack.php',false);
      } else {
        $session->msg("d", "Sorry Failed to insert.");
        redirect('StatusTrack.php',false);
      }
    } else {
      $checkstatusdetails=checkstatusdetails($pla_number,$jobno,$stageold);
      //echo $stagedet;
      //print_r($checkstatusdetails);die();
      $existingId=0;
    foreach($checkstatusdetails as $checks) {
      $existingId=$checks['Id'];
      //echo $checks['Id'];
    } 
      $sql  = "UPDATE trackingdetails SET PlanId={$pla_number},DailyPlanId={$Dailyplanid},JobNo='{$jobno}',SAPCode='{$sapcode}',StageId={$stagedet},TotalQty={$TotalQty},Quantity={$CompletedQty},CompletionDate='{$CompletedDate}',Remarks='{$Remarks}',VendorUnit='{$Vendor}',ChallanNo='{$Challan}',Status={$status},Four={$four},Five={$five},Six={$six},Seven={$seven},Eight={$eight},Nine={$nine},Ten={$ten},Eleven={$eleven},Twelve={$twelve},Thirteen={$thirteen},Fourteen={$fourteen},UserId={$p_userid}";
      $sql .= " Where Id=".$existingId;
      //echo $sql;die();
      if($db->query($sql)){
        $session->msg("s", "Successfully Updated the Plan Status");
        redirect('StatusTrack.php',false);
      } else {
        $session->msg("d", "Sorry Failed to Update.");
        redirect('StatusTrack.php',false);
      }

    }
  
   } else {
     $session->msg("d", $errors);
     redirect('StatusTrack.php',false);
   }
 }

 if(isset($_POST['SPlanId'])){

    $catid  = remove_junk($db->escape($_POST['SPlanId']));
    $fullplandetails = join_salesplan_table_plan($catid);
    
    header('Content-Type: application/json');
    echo json_encode($fullplandetails);
    exit;
    
    }

    if(isset($_GET['DailyId'])){

        $Dailyid = remove_junk($db->escape($_GET['DailyId']));
        $Dailyplandetails1 = join_dailyplan_table_by_Id($Dailyid);
        
        if(isset($Dailyplandetails1)) {
            $i=0;
            $statustracker=[];
            foreach($Dailyplandetails1 as $fplan) {
                //echo $fplan['SAPCode'];
                $sapcode=$fplan['SAPCode'];
                $newstageId='';
                $newstageName='';
                $trackdetails=findstatusdetails($fplan['PlanId'],$fplan['JobNo']);
                if(!empty($trackdetails)) {
                  $stage=$trackdetails[0]['StageId'];
                  $nextstagedetails=findnextstage($sapcode,$fplan['PlanId'],$fplan['JobNo']);
                  //print_r($nextstagedetails);die();
                  $newstageId=$nextstagedetails[0]['nextstage'];
                  $newstageName=$nextstagedetails[0]['StageName'];
                  //echo $newstageId."--".$newstageName;die();
                }
                   $articlestagedetails=articlestagedetails($sapcode,1);
                   foreach($articlestagedetails as $artstage) {
                    $statustracker[$i]['Id']=$fplan['Id'];
                    $statustracker[$i]['PlanId']=$fplan['PlanId'];
                    $statustracker[$i]['PlanName']=$fplan['PlanName'];
                    $statustracker[$i]['TotalQty']=$fplan['CurrentPlan'];
                    $statustracker[$i]['JobNo']=$fplan['JobNo'];
                    $statustracker[$i]['SAPCode']=$fplan['SAPCode'];
                    if($newstageId=='') {
                      $statustracker[$i]['StageId']=$artstage['StageId'];
                      $statustracker[$i]['StageName']=$artstage['Stage'];
                      $statustracker[$i]['OldStageId']='';
                      $statustracker[$i]['OldStageName']='';
                    }else {
                      $statustracker[$i]['StageId']=$newstageId;
                      $statustracker[$i]['StageName']=$newstageName;
                      $statustracker[$i]['OldStageId']=$artstage['StageId'];
                      $statustracker[$i]['OldStageName']=$artstage['Stage'];
                    }

                    $currentplan=$statustracker[$i]['TotalQty'];
                    //print_r($fplan);die();
                    $sizefull=find_by_id_custom("sizedetails",$fplan['SizeId'],'SizeId');

                    $statustracker[$i]['Four']=$currentplan*$sizefull['Four'];
                    $statustracker[$i]['Five']=$currentplan*$sizefull['Five'];
                    $statustracker[$i]['Six']=$currentplan*$sizefull['Six'];
                    $statustracker[$i]['Seven']=$currentplan*$sizefull['Seven'];
                    $statustracker[$i]['Eight']=$currentplan*$sizefull['Eight'];
                    $statustracker[$i]['Nine']=$currentplan*$sizefull['Nine'];
                    $statustracker[$i]['Ten']=$currentplan*$sizefull['Ten'];
                    $statustracker[$i]['Eleven']=$currentplan*$sizefull['Eleven'];
                    $statustracker[$i]['Twelve']=$currentplan*$sizefull['Twelve'];
                    $statustracker[$i]['Thirteen']=$currentplan*$sizefull['Thirteen'];
                    $statustracker[$i]['Fourteen']=$currentplan*$sizefull['Fourteen'];

                   }
                
                $i=$i+1;
            }
        }
        //print_r($statustracker);die();
        
        }

function getDatabaseConnection() {
    $mysqli = new mysqli("localhost", "simplepr_ptpuser", "J4Jasmine@123", "simplepr_ptpmanagement");
    if ($mysqli->connect_errno) {
      die("Database connection failed: " . $mysqli->connect_error);
    }
    return $mysqli;
  }

?>
<?php include_once('layouts/header.php'); ?>

  <div class="row">
     <div class="col-md-12">
       <?php echo display_msg($msg); ?>
     </div>
  </div>
  <div class="row">
  <div class="col-md-12">
      <div class="panel panel-default">
        <div class="panel-heading">
          <strong>
            <span class="glyphicon glyphicon-th"></span>
            <span>Edit Daily Plan</span>
         </strong>
        </div>
        <div class="panel-body">
          <form method="post" action="StatusTrackEdit.php">
          <input type="hidden" class="form-control" name="dailyid" value="<?php echo $Dailyplandetails1[0]['Id']; ?>" >
          <input type="hidden" class="form-control" name="OldStageId" value="<?php echo $statustracker[0]['OldStageId']; ?>" >
          <input type="hidden" class="form-control" name="oldstagename" value="<?php echo $statustracker[0]['OldStageName']; ?>" >
            <div class="row">
            <div class="col-md-4">
            <div class="form-group">
            <label for="Planid">Plan</label> 
            <select id="PlanId" class="form-control" name="planid" onChange="plandetailsselect()" readonly="true">
                      <option value="">Select Plan</option>
                    <?php  foreach ($all_plans as $cat): ?>
                      <option value="<?php echo $cat['PlanId']; ?>" <?php if($Dailyplandetails1[0]['PlanId']==$cat['PlanId']) { ?> Selected <?php } ?> >
                        <?php echo $cat['PlanName'] ?></option>
                    <?php endforeach; ?>
                    </select>
            </div>
            </div>
            <div class="col-md-4">
            <div class="form-group">
            <label for="Job No">Job No:</label>
            <input list="brow" value="<?php echo $Dailyplandetails1[0]['JobNo']; ?>" class="form-control" name="jobno" readonly="true">
            <datalist id="brow">
                <?php for($i=1;$i<=100;$i++) {?>
                <option value="<?php echo "Job ".$i; ?>">
                <?php } ?>
            </datalist>
                <!--<input type="number" class="form-control" name="jobno" placeholder="Enter Job Number">-->
            </div>
            </div>
            <div class="col-md-4">
            <div class="form-group">
            <label for="colour">Stage</label>
            <select id="Color" class="form-control" name="StageId" readonly="true">
                      <option value="">Select Stage</option>
                    <?php  foreach ($all_stage as $clr): ?>
                      <option value="<?php echo $clr['StageId']; ?>" <?php if($statustracker[0]['StageId']==$clr['StageId']) { ?> Selected <?php } ?>>
                        <?php echo $clr['StageName'] ?></option>
                    <?php endforeach; ?>
                    </select>
            </div>
            </div>
            </div>
            
            <div class="row">
            <div class="col-md-4">
            <div class="form-group">
            <label for="initial">Total Quantity</label>
            <input type="text" id="iplan" class="form-control" name="TotalQty" value="<?php echo $Dailyplandetails1[0]['CurrentPlan']; ?>" placeholder="Total Quantity" readonly="true">
            </div>
            </div>
            <div class="col-md-4">
            <div class="form-group">
            <label for="initial">Initial Plan</label>
            <input type="text" id="iplan" class="form-control" name="CompletedQty" value="<?php //echo $Dailyplandetails1[0]['InitialPlan']; ?>" placeholder="Finished Quantity" >
            </div>
            </div>
            <div class="col-md-4">
            <div class="form-group">
            <label for="start-date">Completed Date</label>
                <input type="date" class="form-control" name="daydate" value="<?php //echo $Dailyplandetails1[0]['PlanDate']; ?>" placeholder="Completed Date">
            </div>
            </div>
            <div class="col-md-4">
            <div class="form-group">
            <label for="start-date">Vendor Unit</label>
                <input type="text" class="form-control" name="Vendor" value="<?php //echo $Dailyplandetails1[0]['PlanDate']; ?>" placeholder="Vendor">
            </div>
            </div>
            <div class="col-md-4">
            <div class="form-group">
            <label for="start-date">Challan No:</label>
                <input type="text" class="form-control" name="Challan" value="<?php //echo $Dailyplandetails1[0]['PlanDate']; ?>" placeholder="Challan No">
            </div>
            </div>
            <div class="col-md-4">
            <div class="form-group">
            <label for="colour">Stage</label>
            <select class="form-control" name="status" required>
                      <option value="">Select Status</option>
                      <option value="0" >In Progress</option>
                      <option value="1" >Completed</option>
                    </select>
            </div>
            </div>
            <div class="col-md-4">
            <div class="form-group">
            <label for="start-date">Remarks</label>
                <textarea class="form-control" name="Remarks" value="<?php //echo $Dailyplandetails1[0]['PlanDate']; ?>" placeholder="comment">
                    </textarea >
            </div>
            </div>
            </div>
            
            <div class="row">
            <div class="panel-heading">
          <strong>
            
            <span>Size Wise Pair Count</span>
         </strong>
        </div>
            <div class="col-md-2">
            <div class="form-group">
            <label for="start-date">4</label>
            <input type="text" class="form-control" name="four" value="<?php echo $statustracker[0]['Four']; ?>" placeholder="Enter Value">
            </div>
            </div>
            <div class="col-md-2">
            <div class="form-group">
            <label for="start-date">5</label>
            <input type="text" class="form-control" name="five" value="<?php echo $statustracker[0]['Five']; ?>" placeholder="Enter Value">
            </div>
            </div>
            <div class="col-md-2">
            <div class="form-group">
            <label for="start-date">6</label>
            <input type="text" class="form-control" name="six" value="<?php echo $statustracker[0]['Six']; ?>" placeholder="Enter Value">
            </div>
            </div>
            <div class="col-md-2">
            <div class="form-group">
            <label for="start-date">7</label>
            <input type="text" class="form-control" name="seven" value="<?php echo $statustracker[0]['Seven']; ?>" placeholder="Enter Value">
            </div>
            </div>
            <div class="col-md-2">
            <div class="form-group">
            <label for="start-date">8</label>
            <input type="text" class="form-control" name="eight" value="<?php echo $statustracker[0]['Eight']; ?>" placeholder="Enter Value">
            </div>
            </div>
            <div class="col-md-2">
            <div class="form-group">
            <label for="start-date">9</label>
            <input type="text" class="form-control" name="nine" value="<?php echo $statustracker[0]['Nine']; ?>" placeholder="Enter Value">
            </div>
            </div>
            <div class="col-md-2">
            <div class="form-group">
            <label for="start-date">10</label>
            <input type="text" class="form-control" name="ten" value="<?php echo $statustracker[0]['Ten']; ?>" placeholder="Enter Value">
            </div>
            </div>
            <div class="col-md-2">
            <div class="form-group">
            <label for="start-date">11</label>
            <input type="text" class="form-control" name="eleven" value="<?php echo $statustracker[0]['Eleven']; ?>" placeholder="Enter Value">
            </div>
            </div>
            <div class="col-md-2">
            <div class="form-group">
            <label for="start-date">12</label>
            <input type="text" class="form-control" name="twelve" value="<?php echo $statustracker[0]['Twelve']; ?>" placeholder="Enter Value">
            </div>
            </div>
            <div class="col-md-2">
            <div class="form-group">
            <label for="start-date">13</label>
            <input type="text" class="form-control" name="thirteen" value="<?php echo $statustracker[0]['Thirteen']; ?>" placeholder="Enter Value">
            </div>
            </div>
            <div class="col-md-2">
            <div class="form-group">
            <label for="start-date">14</label>
            <input type="text" class="form-control" name="fourteen" value="<?php echo $statustracker[0]['Fourteen']; ?>" placeholder="Enter Value">
            </div>
            </div>
            </div>

            <button type="submit" name="add_pla" class="btn btn-primary">Update Status</button>
        </form>
        </div>
      </div>
    </div>
</div>
   
  </div>
  <script type="text/JavaScript"> 
  function plandetailsselect() {
      var Catvalue=document.getElementById('PlanId').value;
      console.log(Catvalue);

      $.ajax({
    url      : 'DailyPlan.php',
    data     : {'SPlanId':Catvalue},
    dataType: 'json',
    type     : 'POST',
    success  : function(Result){
              console.log(Result[0]);
              //var myObj = $.parseJSON(Result);
              var myObj =Result;
              $("#Artno").empty();
              $('#Artno').append('<option value="">Select Article </option>');
              $("#Color").empty();
              $('#Color').append('<option value="">Select Stage </option>');
              $("#Size").empty();
              $('#Size').append('<option value="">Select Size </option>');
              //console.log(myObj);
              console.log(Object.keys(myObj).length);
              //you can now access data like this:
              //myObj.Address_1
              $.each(myObj, function (i, value) {
                $('#Artno').append('<option value=' + value.ArticleId + '>' + value.ArticleName + '</option>');
                $('#Color').append('<option value=' + value.StageId + '>' + value.StageName + '</option>');
                $('#Size').append('<option value=' + value.SizeId + '>' + value.SizeAssortment + '</option>');
                $('#iplan').val(value.CaseCount);
            });
        }
    }
  );
    
}
     </script>
  <?php include_once('layouts/footer.php'); ?>
