<?php

// get the required bs_group_structure and connect file


// whichever ledgers we are dealing, get their max(Date), closing balance from act_ledgerbalances where date <= ? (maxdate)

// from the inputs verify if the bs_group_name received actually exists in any of the bs_group_name in the array from structure file
// if yes only then proceed
// foreach on its child ledgerhead
// ledgerhead == 'bs_group_name' {
// get 11 ledgers from this ledgerhead
// if received count == 11,
//  -- ledgerhead_sum_bool = 1 else 0
// } else ledgerhead_sum_bool = 1
// if(ledgerhead_sum_bool == 1) {
// code reference group sumary classified

// get the sum of all debit balances seperately and credit balances seperately for every ledger where ledgerhead = ?
// } else {
// display the ledgers fetched at the above level 
// }

// if the bs_group_name == 'Current Assets'
// mannually append the closing stock to the return data

require_once '../../../../../resources/base_path_include.php';
require_once $base_path . '/modules/accounting/reports/balancesheet/bs_groups_structure.php';

$sql_get_ledger_summary = "SELECT
ld.ledger_name as ledger_name,
lb.ledgerid ,
lb.closing_balance as closing_balance 
FROM
act_ledgerbalances lb
INNER JOIN (
SELECT
    lb1.ledgerid AS ledgerid,
    MAX(lb1.date) AS max_date
FROM
    act_ledgerbalances lb1
WHERE
    lb1.workspace_id = ?
    AND lb1.company_id = ?
    AND lb1.branch_id = ?
    AND lb1.book_id = ?
    AND lb1.main_ledgerhead = ?
    AND lb1.date <= ?
GROUP BY
    lb1.ledgerid
LIMIT 11
) AS abc
ON
lb.ledgerid = abc.ledgerid
AND lb.date = abc.max_date
INNER JOIN act_ledgerdetails ld ON ld.id = lb.ledgerid;";
$get_ledger_summary = $specific_db_conn->prepare($sql_get_ledger_summary);


//  get the sum of all debit balances seperately and credit balances seperately 
$sql_get_sum_ledgerheads = "SELECT
SUM(CASE WHEN closing_balance > 0 THEN closing_balance ELSE 0 END) AS positive_closing_balance,
SUM(CASE WHEN closing_balance < 0 THEN closing_balance ELSE 0 END) AS negative_closing_balance
FROM (
SELECT
    lb.closing_balance
FROM
    act_ledgerbalances lb
INNER JOIN (
    SELECT
        ledgerid,
        MAX(date) AS max_date
    FROM
        act_ledgerbalances
    WHERE
        workspace_id = ?
        AND company_id = ?
        AND branch_id = ?
        AND book_id = ?
        AND main_ledgerhead = ?
        AND date <= ?
    GROUP BY
        ledgerid
) AS max_dates
ON
    lb.ledgerid = max_dates.ledgerid
    AND lb.date = max_dates.max_date
) AS subquery";
$get_sum_ledgerheads = $specific_db_conn->prepare($sql_get_sum_ledgerheads);

function ClassifiedBsGroupSummary($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $mindate, $maxdate, $bs_group_selected, $valuation_method)
{
    $summary_data = [];
    $total_debit_closing = 0.00;
    $total_credit_closing = 0.00;

    if ($bs_group_selected['bs_group_name'] == 'Current Assets') {
        // closing stock calculation
        {
            // include valuation_method file
            if ($valuation_method == 'FIFO') {
                require_once '../../valuation_methods/closing_stock_summary/fifo_summary_function.php';
                $stock_object = getFifoSummaryClosingStock($specific_db_conn, $mindate, $maxdate, $workspace_id, $company_id, $branch_id, $book_id);
            } else if ($valuation_method == 'LIFO') {
                require_once '../../valuation_methods/closing_stock_summary/lifo_summary_function.php';
                $stock_object = getFifoSummaryClosingStock($specific_db_conn, $mindate, $maxdate, $workspace_id, $company_id, $branch_id, $book_id);
            } else if ($valuation_method == 'AVG_CP') {
                require_once '../../valuation_methods/closing_stock_summary/avg_cp_summary_function.php';
                $stock_object = getAvgCpSummaryClosingStock($specific_db_conn, $mindate, $maxdate, $workspace_id, $company_id, $branch_id, $book_id);
            }

            if ($stock_object['status'] == 1) {
                $closing_stock = $stock_object['closing_stock'];
                $opening_stock = $stock_object['opening_stock'];
                if ($closing_stock != 0) {
                    $bs_group_data_specific['data'][] = [
                        "type" => "closing_stock",
                        "clickable" => false,
                        "name" => "Closing Stock",
                        "net_closing_balance" => $closing_stock
                    ];
                    if ($closing_stock >= 0) {
                        $temp_closing_stock_debit = $closing_stock;
                        $temp_closing_stock_credit = 0.00;
                        $total_debit_closing += $closing_stock;
                    } else {
                        $temp_closing_stock_credit = $closing_stock;
                        $temp_closing_stock_debit = 0.00;
                        $total_credit_closing += $closing_stock;
                    }
                    $summary_data[] = array('type' => 'closing_stock', 'clickable' => false, 'name' => 'Closing Stock', 'credit_closing' => $temp_closing_stock_credit, 'debit_closing' => $temp_closing_stock_debit);
                }
            } else {
                errorreturn('Error in calculating stock valuation.');
            }
        }
    }

    // traversing through each child ledgerhead
    foreach ($bs_group_selected['children'] as $ledgerhead) {

        if ($ledgerhead == $bs_group_selected['bs_group_name']) {
            // get the count of ledgers
            $GLOBALS['get_ledger_summary']->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerhead, $maxdate));
            $result_get_ledger_summary = $GLOBALS['get_ledger_summary']->fetchAll();
            if (count($result_get_ledger_summary) == 11) {
                $ledgerhead_sum_bool = 1;
            } else $ledgerhead_sum_bool = 0;
        } else {
            $ledgerhead_sum_bool = 1;
        }

        if ($ledgerhead_sum_bool == 1) {

            $GLOBALS['get_sum_ledgerheads']->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerhead, $maxdate));
            $result_get_sum_ledgerheads =  $GLOBALS['get_sum_ledgerheads']->fetchAll();
            $total_credit_closing += abs($result_get_sum_ledgerheads[0]['negative_closing_balance'] ?? 0);
            $total_debit_closing += abs($result_get_sum_ledgerheads[0]['positive_closing_balance'] ?? 0);

            if (abs($result_get_sum_ledgerheads[0]['negative_closing_balance'] ?? 0) != 0 or abs($result_get_sum_ledgerheads[0]['positive_closing_balance'] ?? 0 ) != 0) {

                $summary_data[] = array('type' => 'group', 'clickable' => true, 'name' => $ledgerhead, 'credit_closing' => abs($result_get_sum_ledgerheads[0]['negative_closing_balance']), 'debit_closing' => abs($result_get_sum_ledgerheads[0]['positive_closing_balance']));
            }
        } else {
            // get the ledgers
            foreach ($result_get_ledger_summary as $row_temp_ledgers) {

                if ($row_temp_ledgers['closing_balance'] > 0) {
                    $summary_data[] = array('type' => 'ledger', 'clickable' => true, 'ledger_id' => $row_temp_ledgers['ledgerid'], 'name' => $row_temp_ledgers['ledger_name'], 'credit_closing' => 0, 'debit_closing' => abs($row_temp_ledgers['closing_balance']));
                    $total_debit_closing += $row_temp_ledgers['closing_balance'];
                } elseif ($row_temp_ledgers['closing_balance'] < 0) {
                    $summary_data[] = array('type' => 'ledger', 'clickable' => true, 'ledger_id' => $row_temp_ledgers['ledgerid'], 'name' => $row_temp_ledgers['ledger_name'], 'credit_closing' => abs($row_temp_ledgers['closing_balance']), 'debit_closing' => 0);
                    $total_credit_closing += $row_temp_ledgers['closing_balance'];
                }
            }
        }
    }

    return array('bs_group_name' => $bs_group_selected['bs_group_name'], 'data' => $summary_data, 'debit_total_closing' => abs($total_debit_closing), 'credit_total_closing' => abs($total_credit_closing));
}
