<?php
 
////////////////////////////////////////////// Database Connector /////////////////////////////////////////////////////////////
require_once ("connection_sql.php");


date_default_timezone_set('Asia/Colombo');
 

// $item='ATL00005';
// $invqty=3;
// $totinvqty=3;  
 
// $sql1 = "select * from s_purtrn where STK_NO='" . $item . "' and CANCEL='0' ORDER BY ID DESC"; 
// foreach ($conn->query($sql1) as $row1) {

//     if($row1['REC_QTY']>=$invqty ){ 
//         $recval +=$invqty*$row1['COST'];
//         break;
//     }else { 
//         $recval +=$row1['REC_QTY']*$row1['COST'];
//         $invqty=$invqty-$row1['REC_QTY'];
//     }    

// }

 

// $unitcost=$recval/$totinvqty;

// echo $unitcost;


// ===================


        
$sqlmas_f = "select * from s_mas"; 
foreach ($conn->query($sqlmas_f) as $rowmas_f) {
    
$costitemfinal=0;
$invqtyfinal=0;
$totinvqtyfinal=0;
$unitcostfinal=0;
$recvalfinal=0;

    if($rowmas_f['BRAND_NAME']=="SERVICE"){ 
        $costitemfinal=0;
    }else{
        $costitemfinal=$rowmas_f["COST"];
        $invqtyfinal=$rowmas_f['QTYINHAND'];
        $totinvqtyfinal=$rowmas_f['QTYINHAND'];
         
        $sqlpurtrn_f = "select * from s_trn where STK_NO='" . $rowmas_f['STK_NO'] . "' AND LEDINDI='ARN' ORDER BY ID DESC"; 
         foreach ($conn->query($sqlpurtrn_f) as $row_purtrn_f) {
        
            if($row_purtrn_f['QTY']>=$invqtyfinal ){ 
                $recvalfinal +=$invqtyfinal*$row_purtrn_f['cost'];
                break;
            }else { 
                $recvalfinal +=$row_purtrn_f['QTY']*$row_purtrn_f['cost'];
                $invqtyfinal=$invqtyfinal-$row_purtrn_f['QTY'];
            }    
        
        }
        $unitcostfinal=$recvalfinal/$totinvqtyfinal;
        
        $costitemfinal=$unitcostfinal;
        
          
        
        $sqls_mas="update s_mas set acc_cost= '".$costitemfinal."' where STK_NO='".trim($rowmas_f['STK_NO'])."'";
       $result_mas = $conn->query($sqls_mas);
       
       echo $sqls_mas.'<br>';
    }

}





//  ==============================
// last cost update

// $cost=0;
// $sql1 = "select * from s_mas"; 
// foreach ($conn->query($sql1) as $row1) {
//      $sql3 = "select COST,STK_NO from s_purtrn where STK_NO='" . $row1['STK_NO'] . "' and CANCEL='0' ORDER BY ID DESC"; 
//     $result3 = $conn->query($sql3);
//     $row3 = $result3->fetch();
    
//     $cost=$row3['COST'];

//  $sql="update s_mas set COST= '".$cost."' where STK_NO='".trim($row1['STK_NO'])."'";
//  $result = $conn->query($sql);
 
// }
?>