<?php
require_once('includes/load.php');

$article='2-FB-3058-BK-G1';
$casecount=100;
$unitname='FORTUNE ELASTOMERS PVT.LTD - KINALOOR';
$PlanId=13;
$unitid=5;

function intermediatestagecalculation($PlanId, $unitid, $article,$unitname) {

//$products = join_salesplan_table();

$insertadd = 0;
//$trigbom = selectbomtocreate();

$db1 = getDatabaseConnection1();
  //$query = "SELECT * FROM draftplandetails WHERE ArticleSAPCode='" . $article . "'";
  //$avlqtyarray = $db1->query($query);

$sql = "CALL intermediatearticlecalculation('{$article}', '{$unitname}')";
$bomrow = $db1->query($sql);
//print_r($bomrow);die();
 
  foreach ($bomrow as $avl) {
    $avlQty = 0;
    $db1 = getDatabaseConnection1();
    $stmt = $db1->prepare("CALL GetMaterialDetailsByArticleCode(?, ?)");
    $stmt->bind_param("ss", $avl['child'], $unitname);
    $stmt->execute();
    $result = $stmt->get_result();
    $sapdatafetchavl = $result->fetch_assoc();
    $stmt->close();
    $db1->close();
   
    if (isset($sapdatafetchavl['avlstock'])) {
      $avlQty = $sapdatafetchavl['avlstock'];
    }

    //$db1 = getDatabaseConnection1();
    //$query  = "INSERT INTO intermediatearticles (";
    //$query .="article,avlqty";
    //$query .=") VALUES (";
    //$query .=" '{$avl['child']}', {$avlQty}";
    //$query .=")";
    //$db->query($query);

    $db1 = getDatabaseConnection1();
    $stmt = $db1->prepare("CALL Insertintermediate(?, ?, ?, ?)");
    $stmt->bind_param("siii", $avl['child'], $avlQty,$PlanId,$unitid);
    $stmt->execute();
    $stmt->close();
    $db1->close();
  }

  $db1 = getDatabaseConnection1();
  $query = "SELECT * FROM intermediatearticles where avlqty>0";
  $avlqtyarray = $db1->query($query);
 
  foreach ($avlqtyarray as $avl) {
    $db1 = getDatabaseConnection1();
    $sql = "CALL rowmaterialcalculation('{$avl['article']}', {$avl['avlqty']}, '{$unitname}')";
    $bomrow1 = $db1->query($sql);

    foreach ($bomrow1 as $avlinter) {
        //echo $avl['article'],"---",$avlinter['ReqQty'],"::", $avlinter['child'],"\n";
        $db1 = getDatabaseConnection1();
        $stmt = $db1->prepare("CALL UpdateIntermediate(?, ?, ?, ?)");
        $stmt->bind_param("dsii", $avlinter['ReqQty'], $avlinter['child'],$PlanId,$unitid);
        $stmt->execute();
        $stmt->close();
        $db1->close();

    }
    //print_r($bomrow);die();
  }
//die();
  //$db1 = getDatabaseConnection1();
    //$stmt = $db1->prepare("CALL UpdateDraftPlanDetailsAvlStock(?, ?, ?, ?)");
    //$stmt->bind_param("iisd", $PlanId, $unitid, $avl['SAPCode'], $avlQty);
    //$stmt->execute();
    //$stmt->close();
    //$db1->close();

}

function getDatabaseConnection1() {
    $mysqli = new mysqli("localhost", "root", "", "vishnum1_materials_requirement_managementfull");
    if ($mysqli->connect_errno) {
      die("Database connection failed: " . $mysqli->connect_error);
    }
    return $mysqli;
  }
?>