<?php
$page_title = 'Draft Plan';
require_once('includes/load.php');
// Checking what level user has permission to view this page
page_require_level(1);

if (isset($_POST['planid'])) {
$selectedPlan = $_POST['planid'];
$selectedUnit = $_POST['unitid'];

if ($selectedPlan && $selectedUnit) {
  echo $selectedPlan; // Move this line inside the if condition

  // Fetch plan name from plandetails table
  $plan = find_by_columnnew('plandetails', $selectedPlan, 'PlanId');
  $planName = isset($plan['PlanName']) ? $plan['PlanName'] : '';

  // Fetch unit name from unitdetails table
  $unit = find_by_columnnew('unitdetails', $selectedUnit, 'UnitId');
  $unitName = isset($unit['UnitName']) ? $unit['UnitName'] : '';

  // Fetch data from draftplandetails table based on the selected plan and unit
  $draftPlanDetails = find_by_fields('draftplandetails', array('planid' => $selectedPlan, 'unitid' => $selectedUnit));

  $bomcreation = bomtablecreationstatuscheck($selectedPlan,$selectedUnit);
    if(!empty($bomcreation)) {

      $error_message =array('danger'=>' Draft plan creation is in progress!');
        //redirect('choosedraftplan.php', false);
    } else {
            //$bomcreation = bomtablecreation($planids,$unitids);
            $error_message =array('success'=>"Draft plan creation completed successfully! ");
            
    }

} else {
  $error_message = 'Please select a plan and unit.';
}
}

// Handle approve button click
if (isset($_POST['approve'])) {
  $insertadd=0;
  $insertadd1=0;
  // Update the status column to 1 for the selected plan and unit

  $del_PlanId=$_POST['planid'];
  $del_UnitId=$_POST['unitid'];

  $draftPlanDetailsaprrove = find_by_fields('draftplandetails', array('planid' => $_POST['planid'], 'unitid' => $_POST['unitid']));
  if(!empty($draftPlanDetailsaprrove)) {
      foreach($draftPlanDetailsaprrove as $planitem) {
        //print_r($planitem);die();
        $query  = "INSERT INTO planarticlemapping (";
        $query .=" PlanId,UnitId,SAPCode,Quantity,Status";
        $query .=") VALUES (";
        $query .=" {$planitem['PlanId']}, {$planitem['UnitId']}, '{$planitem['SAPCode']}', {$planitem['ReqStock']}, 0";
        $query .=")";
        $query .=" ON DUPLICATE KEY UPDATE Quantity= {$planitem['ReqStock']},Status=0";

        if($db->query($query)){
          $insertadd=1;
        } else {
          $insertadd=0;
        }
        $poalloc=0;
        if(isset($planitem['POQty'])) {
          if(($planitem['AvlStock']+$planitem['AvlInterQty'])<$planitem['ReqStock']) {
            if($planitem['ReqStock']<$planitem['POQty']) {
              $poalloc=$planitem['ReqStock']-($planitem['AvlStock']+$planitem['AvlInterQty']);
            } else {
              $poalloc=$planitem['POQty'];
            }
          }
        }

        $query1  = "INSERT INTO planpomapping (";
        $query1 .=" PlanId,UnitId,SAPCode,Quantity,Status";
        $query1 .=") VALUES (";
        $query1 .=" {$planitem['PlanId']}, {$planitem['UnitId']}, '{$planitem['SAPCode']}', {$poalloc}, 0";
        $query1 .=")";
        $query1 .=" ON DUPLICATE KEY UPDATE Quantity= {$poalloc},Status=0";

        if($db->query($query1)){
          $insertadd1=1;
        } else {
          $insertadd1=0;
        }

        //print_r($planitem);die();
      }

      $query2="DELETE FROM intermediatearticles WHERE PlanId=".$del_PlanId." and UnitId=".$del_UnitId;
      $db->query($query2);
  }
  
  //print_r($draftPlanDetailsaprrove);die();

 $approveStatus = update_status_approve_plan($_POST['planid'],  $_POST['unitid'], 1);
 if($approveStatus){
    //sucess
    $session->msg('s',"Successfully approved");
    redirect('showdraftplan_getInput.php', false);
  } else {
    //failed
    $session->msg('d',' Failed to approve');
    redirect('showdraftplan_getInput.php', false);
  }
}

if(isset($_GET['excel'])) {
  
  $planid=$_GET['PlanId'];
  $unitid=$_GET['UnitId'];

  $results=draft_plan_export($planid,$unitid);

  $tasks = array();
  while( $rows = mysqli_fetch_assoc($results) ) {
  $tasks[] = $rows;
  }

  $filename = "MM_Reqirement_Draft_Plan_export_".date('Ymd') . ".xls";
      header("Content-Type: application/vnd.ms-excel");
  header("Content-Disposition: attachment; filename=\"$filename\"");
  ExportFile($tasks);
  //print_r($tasks);
  //echo "yes";die();

}


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

<div class="row">
  <div class="col-md-12">
    <?php
    if (isset($error_message)) {
      echo display_msg($error_message);
    }
    ?>
  </div>
  <div class="col-md-12">
    
    <?php if (isset($selectedPlan) && isset($selectedUnit) && isset($draftPlanDetails)) : ?>
      <div class="panel panel-default">
        <div class="panel-heading clearfix">
         <div class="pull-right">
		   <a href="showdraftplan.php?excel=1&PlanId=<?php echo $selectedPlan; ?>&UnitId=<?php echo $selectedUnit;?>" class="btn btn-primary">Export</a>
           <!--<a href="Product_Add.php" class="btn btn-primary">Add New</a>--->
         </div>
        </div>
      <h4>Selected Plan: <?php echo $planName; ?></h4>
      <h4>Selected Unit: <?php echo $unitName; ?></h4>
      <form method="POST" action="">
        <table id="salesplantable" class="table table-bordered table-striped table-hover">
          <thead>
            <tr>
              <th class="text-center" style="width: 10%;">#</th>
              <th class="text-center" style="width: 10%;">SAP Code</th>
              <th class="text-center" style="width: 10%;">Actual Stock Required</th>
              <th class="text-center" style="width: 10%;">Available Stock</th>
              <th class="text-center" style="width: 10%;">Available Stock In Intermediate Items</th>
              <th class="text-center" style="width: 10%;">Allocated Stock</th>
              <th class="text-center" style="width: 10%;">PO Stock</th>
              <th class="text-center" style="width: 10%;">Allocated PO Stock</th>
              <th class="text-center" style="width: 10%;">Expected Stock Required</th>
              <th class="text-center" style="width: 10%;">Status</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($draftPlanDetails as $index => $detail) : ?>
              <tr>
                <td class="text-center"><?php echo $index + 1; ?></td>
                <td class="text-center"><?php echo $detail['SAPCode']; ?></td>
                <td class="text-center"><?php echo $detail['ReqStock']; ?></td>
                <td class="text-center"><?php echo $detail['AvlStock']; ?></td>
                <td class="text-center"><?php echo $detail['AvlInterQty']; ?></td>
                <td class="text-center"><?php echo $detail['AlocStock']; ?></td>
                <td class="text-center"><?php echo $detail['POQty']; ?></td>
                <td class="text-center"><?php echo $detail['AlocPOStock']; ?></td>
                
                <td class="text-center"><?php if(($detail['AvlStock'] + $detail['AvlInterQty']) > $detail['ReqStock']) {
                  echo 0;
                }  else {
                  if($detail['ReqStock']<$detail['POQty']) {
                    echo 0;
                  } else {
                  echo $detail['ReqStock']-(($detail['AvlStock'] + $detail['AvlInterQty'])-$detail['POQty']);
                  }
                }
                ?></td>
                <td class="text-center"><?php if($detail['Status']==0){echo "Draft";} else if($detail['Status']==1) {echo "Approved";} else if($detail['Status']==2) {echo "Completed";} ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
        <input type="hidden" name="planid" value="<?php echo $selectedPlan; ?>" />
        <input type="hidden" name="unitid" value="<?php echo $selectedUnit; ?>" />
        <input type="submit" name="approve" class="btn btn-success" value = "Approve"/>
      </form>
    <?php endif; ?>
  </div>
</div>

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