<?php
ini_set('display_errors', 1);

/*

1. Initialize variables:
   - lifo_inventory = []  # A list to represent the LIFO inventory
   - total_purchase_qty = 0
 
2. For each transaction (purchase) in chronological order:
   - Read transaction date, transaction type, quantity, unit price
 
   If transaction type is "purchase":
   	- Increment total_purchase_qty by quantity
   	- Add (quantity, unit price) to the lifo_inventory list
 
3. Read specific date for closing stock calculation.
 
4. For each transaction (sale) on or before the specific date:
   - Read transaction date, transaction type, quantity
 
   If transaction type is "sales":
   	- While quantity > 0 and lifo_inventory is not empty:
       	- Read lifo_qty (quantity in LIFO), lifo_price (price in LIFO)
       	- If lifo_qty <= quantity:
           	- Decrement quantity by lifo_qty
           	- Remove lifo_qty from lifo_inventory
   	    - Else:
           	- Subtract quantity from lifo_qty
           	- Update lifo_qty in lifo_inventory
 
5. Calculate closing stock value on the specific date:
   - closing_stock_value = Sum of (lifo_qty * lifo_price) for each remaining item in lifo_inventory
 
6. Display closing stock value on the specific date.

*/

// needs addition of non inventory boolean support and addition of closing stock with openingbalance before every foreach

function getLifoSummaryClosingStock($specific_db_conn, $mindate, $maxdate, $workspace_id, $company_id, $branch_id, $book_id)
{

  // this function only gives one closing_stock_value for the maxdate for only inventory_applicable items
  $closing_stock = 0.00;

  $opening_stock = 0.00;

  // preparing basic queries 
  $sql_fetch_transactions_chronological = "Select qty, per_price, total_amount from inventory_stocktransaction where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and stock_id = ? and date <= ? order by date, id";
  $fetch_transactions_chronologial = $specific_db_conn->prepare($sql_fetch_transactions_chronological);

  $sql_fetch_stock_items = "Select id, opening_bal from inventory_stockdetails where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and boolean_inventory = ?";
  $fetch_stock_items = $specific_db_conn->prepare($sql_fetch_stock_items);
  $fetch_stock_items->execute(array($workspace_id, $company_id, $branch_id, $book_id, 1));
  $result_stock_items = $fetch_stock_items->fetchAll();
  if (count($result_stock_items) <= 0) {
    return array('closing_stock' => $closing_stock, 'opening_stock' => $opening_stock);
  }


  foreach ($result_stock_items as $row_stock_items) {
    $stock_id = $row_stock_items['id'];

    $opening_stock += $row_stock_items['opening_bal'];

    $total_purchase_qty = 0.00; // initially set to 0 for each item
    $last_purchase_price = 0.0; // initially set to 0 for each item
    $temp_stock_list = [];
    $temp_negative_stock_list = [];

    $fetch_transactions_chronologial->execute(array($workspace_id, $company_id, $branch_id, $book_id, $stock_id, $maxdate));
    $result_transactions_chronological = $fetch_transactions_chronologial->fetchAll();
    foreach ($result_transactions_chronological as $row_transaction) {
      if ($row_transaction['type'] == 'purchase') {
        $total_purchase_qty += $row_transaction['qty'];
        $temp_stock_list[] = array('quantity' => $row_transaction['qty'], 'per_price' => $row_transaction['per_price']);

        $last_purchase_price = $row_transaction['per_price'];
      }
      if ($row_transaction['type'] == 'sales') {
        $deduct_qty = $row_transaction['qty']; // used as counter to iterate over loop

        while ($deduct_qty > 0) {
          if (count($temp_stock_list) <= 0) {
            // case of negative qty
            $temp_negative_stock_list[] = array('quantity' => $deduct_qty, 'per_price' => $last_purchase_price);
          } else {
            // case of positive qty
            if ($temp_stock_list[count($temp_stock_list) - 1]['qty'] > $deduct_qty) {
              // just deduct and move ahead
              $temp_stock_list[count($temp_stock_list) - 1]['qty'] -= $row_transaction['qty'];
            } else if ($temp_stock_list[count($temp_stock_list) - 1]['qty'] <= $deduct_qty) {
              // remove the item as deduct qty is greater
              array_pop($temp_stock_list);
            }
          }
          $deduct_qty -= $row_transaction['qty'];
        }
      }
    }
    foreach ($temp_stock_list as $element) {
      $closing_stock += ($element['qty'] * $element['per_price']);
    }

    foreach ($temp_negative_stock_list as $element) {
      $closing_stock -= ($element['qty'] * $element['per_price']);
    }
  }
  return array('closing_stock' => $closing_stock, 'opening_stock' => $opening_stock);
}
