<?php
$stockrecord = $postdata['stockrecord'];
// movement type from stands for source and to stands for destination
function validateInterRegionStock($conn, $workspace_id, $company_id, $branch_id, $book_id, $stockrecord, $transactiontype)
{

    $stock_sql = $conn->prepare("SELECT id,current_qty,default_tax_ledgerid,unit_id FROM inventory_stockdetails WHERE id = ? and  workspace_id  =? and company_id= ? and  branch_id =? and book_id =?");

    $sql_region = "Select *  from  inventory_region_details where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ?  and id = ?";

    $new_stock_record = array();
    $total_from = 0.00;
    $total_to = 0.00;
    $total_amount = 0.00;
    $total_untaxed_from = 0.00;
    $amount= 0.00;
        
    foreach ($stockrecord as $item) {
        
        $stock_id = $item['stock_id'];
        $region_id = $item['region_id'];

        $stmt_region = $conn->prepare($sql_region);
        $stmt_region->execute(array($workspace_id, $company_id, $branch_id, $book_id, $region_id));
        $result_region = $stmt_region->fetchAll();

        if (count($result_region) != 1) {
            errorreturn("Invalid regions selected.");
        }

        $stock_sql->execute(array($stock_id, $workspace_id, $company_id, $branch_id, $book_id));
        $result1 = $stock_sql->fetchAll();
        
        if (count($result1) != 1) {
            errorreturn('stock items found.');
        } 
        else {
             
            $existing_unit_id = $result1[0]['unit_id'];
            
            // if movement is not there.
            
            if($existing_unit_id == null) {
                
                $total_amount=$item['per_price'];
                if($item['movement']=='from')
                    //$total_amount=-($total_amount);
                $new_stock_record[] = array('stock_id' => $stock_id, 'qty' => null, 'per_price' => null, 'total_amount' => $total_amount, 'unit_id' => null, 'tax_amount' => null, 'movement' => $item['movement'], 'ledgerid' => null, 'region_id' => $region_id);
                
                
                if($item['movement'] == 'from'){
                // case of from
                     $total_untaxed_from += $amount;
                     $total_from += $total_amount;
                 } else{
                    
                     $total_to += $total_amount;
                 }
                
            }
            
            else{
               
                $qty = (isset($item['qty']) and !empty($item['qty'])) ? trim($item['qty']) : null;
                $per_price = (isset($item['per_price']) and !empty($item['per_price'])) ? trim($item['per_price']) : null;
                // user will send tax percentage here, compare it with defaultt tax ledgerid, if true ok, else give error
                $existing_default_tax_ledgerid = (isset($result1[0]['default_tax_ledgerid']) and !empty($result1[0]['default_tax_ledgerid'])) ? trim($result1[0]['default_tax_ledgerid']) : null;

                $res = $conn->prepare("SELECT id,param_1 FROM act_ledgerdetails WHERE id = ? and  workspace_id  =? and company_id= ? and  branch_id =? and book_id =?");
                $res->execute(array($existing_default_tax_ledgerid, $workspace_id, $company_id, $branch_id, $book_id));
                $ledger_result = $res->fetchAll();
                
                if(count($ledger_result) == 1) {
                    $ledgerid = (isset($ledger_result[0]['id']) and !empty($ledger_result[0]['id'])) ? trim($ledger_result[0]['id']) : null;

                    $tax_percentage = (isset($ledger_result[0]['param_1']) and !empty($ledger_result[0]['param_1'])) ? trim($ledger_result[0]['param_1']) : null;
                 
                // calculate new amount = qty * per price + tax_percentage
    
                }
                
                $total_untaxed_from = 0.00;
                $amount = $per_price * $qty;
                //with gst
                if($item['movement'] == 'from')
                    $tax_amount = (is_numeric($per_price) * is_numeric($tax_percentage) / 100) * $qty;
                else
                    $tax_amount = 0;
                    
                $total_amount = $amount + $tax_amount;
             

                $new_stock_record[] = array(
                    'stock_id' => $stock_id, 'qty' => $qty, 'per_price' => $per_price, 'total_amount' => $total_amount, 'unit_id' => $existing_unit_id, 'tax_amount' => $tax_percentage,
                    'movement' => $item['movement'],  'ledgerid' => $ledgerid, 'region_id' => $region_id);
                
                if($item['movement'] == 'from'){
                // case of from
                     $total_untaxed_from += $total_amount;
                     $total_from += $total_amount;
                 } else{
                    
                     $total_to += $total_amount;
                 }
            }
 
        }
       
    }
     
  
     //   echo $total_from;die();
        
    if($total_from !=  $total_to) {
      
        errorreturn("stock amount does not match.");
    }
    return array('stock_record' => $new_stock_record);
}



if ($transactiontype == "inter_region_stock") {
    if ($stockrecord != null and is_array($stockrecord)) {

        //stock transaction add
        $new_stock_record = validateInterRegionStock($conn, $workspace_id, $company_id, $branch_id, $book_id, $stockrecord, $transactiontype);

        $stock_record = $new_stock_record['stock_record'];

        $unique_id =  InsertTransactionData($conn, $workspace_id, $company_id, $branch_id, $book_id, $transactiontype, $transaction_number, $date, $username, $filesattached, $last_modified_by, $narration, $userid);

        // presence of each stock item with the mentioned quantity to be available in system at the from region
        foreach ($stock_record as $rows) {
            $stock_id = $rows['stock_id'];
            $qty = floatval(trim($rows['qty']));

            $per_price = $rows['per_price'];
            $total_amount = $rows['total_amount'];
            $unit_id = $rows['unit_id'];
            $tax_amount = $rows['tax_amount'];
            $ledgerid = $rows['ledgerid'];
            $region_id = $rows['region_id'];
            $tax_percentage = $rows['tax_amount'];
             $description = (isset($rows['description']) and !empty($rows['description'])) ? trim($rows['description']) : null;
              

            if ($rows['movement'] == 'from') {
                //form region
                InsertStockTransactionDetails($conn, $workspace_id, $company_id, $branch_id, $book_id, $stock_id, - ($qty), $per_price, $total_amount, $unit_id, $tax_percentage, $ledgerid,$description, $book_opening_date, $transactiontype, $unique_id, $region_id);
            } else {
                //to region

                InsertStockTransactionDetails($conn, $workspace_id, $company_id, $branch_id, $book_id, $stock_id, $qty, $per_price, $total_amount, $unit_id, $tax_percentage, $ledgerid,$description, $book_opening_date, $transactiontype, $unique_id, $region_id,$description);
            }
        }
    }
    successreturn(array('unique_id' => $unique_id, 'successmsg' => "Transaction saved successfully."));
}
