<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Balancesheet extends Admin_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('studentfeemaster_model');
    }

    private function calculate_net_profit($feeData, $customerData, $discountData, $journalData, $uniformData, $cosData, $supplierData, $expenseData) {
        // Calculate fees total
        $fees_total = 0;
        $processed_invoices = [];
        foreach ($feeData as $invoice) {
            if (!isset($processed_invoices[$invoice['id']])) {
                $processed_invoices[$invoice['id']] = true;
                $fees_total += $invoice['invoice_amount'];
            }
        }

        // Calculate customer income and discounts
        $customer_total = 0;
        $discount_total = 0;
        foreach ($customerData as $customer_invoice) {
            if (isset($customer_invoice['quantity'], $customer_invoice['price'])) {
                $invoice_total = $customer_invoice['quantity'] * $customer_invoice['price'];
                if (isset($customer_invoice['discount'])) {
                    $discount_total += ($customer_invoice['discount'] / 100) * $invoice_total;
                }
                $customer_total += $invoice_total;
            }
        }

        // Calculate fee discounts and fines
        $fine_total = 0;
        foreach ($discountData as $fee_discount) {
            if (isset($fee_discount['amount_discount'])) {
                $discount_total += $fee_discount['amount_discount'];
            }
            if (isset($fee_discount['amount_fine'])) {
                $fine_total += $fee_discount['amount_fine'];
            }
        }

        // Calculate uniforms
        $uniform_total = 0;
        foreach ($uniformData as $uniform) {
            if (isset($uniform['quantity'], $uniform['amount'])) {
                $uniform_total += $uniform['quantity'] * $uniform['amount'];
            }
        }

        // Calculate returns
        $sales_returns_total = 0;
        $fees_returns_total = 0;
        foreach ($journalData as $journal) {
            if (isset($journal['credit'])) {
                $name = strtolower(trim($journal['cashbook']));
                if ($name === 'sales returns journal') {
                    $sales_returns_total += $journal['credit'];
                } elseif ($name === 'learner returns') {
                    $fees_returns_total += $journal['credit'];
                }
            }
        }

        // Total Revenue
        $total_revenue = ($customer_total + $fees_total + $uniform_total + $fine_total)
                       - ($sales_returns_total + $fees_returns_total + $discount_total);

        // Calculate COS
        $total_COS = 0;
        foreach ($cosData as $cos) {
            $lineAmt = (float)($cos['amount'] ?? 0);
            if ($lineAmt != 0) {
                $total_COS += $lineAmt;
            }
        }

        // Calculate COGS
        $total_Materials = 0;
        $total_Labor = 0;
        foreach ($supplierData as $supplier) {
            if (isset($supplier['price'], $supplier['quantity'])) {
                $cogs_amount = $supplier['price'] * $supplier['quantity'];
                if (stripos($supplier['description'] ?? '', 'labor') !== false) {
                    $total_Labor += $cogs_amount;
                } else {
                    $total_Materials += $cogs_amount;
                }
            }
        }
        $total_COGS = $total_Materials + $total_Labor;

        // Gross Profit
        $gross_profit = $total_revenue - $total_COS - $total_COGS;

        // Calculate Expenses
        $total_expense = 0;
        foreach ($expenseData as $expense) {
            if ($expense['module'] === 'GL') {
                $amount = max((float)($expense['debit'] ?? 0), (float)($expense['credit'] ?? 0));
                $total_expense += $amount;
            }
        }

        // Operating Profit
        $operating_profit = $gross_profit - $total_expense;

        // Other Income
        $other_income_total = 0;
        foreach ($journalData as $journal) {
            if (isset($journal['debit'], $journal['description']) && 
               stripos($journal['description'], 'other income') !== false) {
                $other_income_total += $journal['debit'];
            }
        }

        return $operating_profit + $other_income_total;
    }

    public function searchbalancesheet() {
        $this->session->set_userdata('top_menu', 'Financial Reports');
        $this->session->set_userdata('sub_menu', 'balancesheet/searchbalancesheet');
        $data['title'] = 'Search Balance Sheet';
        $data['payment_modes'] = $this->payment_methods_model->select();

        if ($this->input->server('REQUEST_METHOD') == "POST") {
            $search = $this->input->post('search');
            if ($search == "search_filter") {
                $date_from = date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('date_from')));
                $date_to = date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('date_to')));
                
                // Fetch current period data (original fields maintained)
                $data['feeList'] = $this->studentfeemaster_model->getFeesummary($date_from, $date_to);
                $data['customerIncomeList'] = $this->studentfeemaster_model->customer_income($date_from, $date_to)->result_array();
                $data['feediscount'] = $this->studentfeemaster_model->getFeeBetweenDate($date_from, $date_to);
                $data['journalList'] = $this->studentfeemaster_model->getAlljournals($date_from, $date_to)->result_array();
                $data['uniformList'] = $this->studentfeemaster_model->getAlluniforms($date_from, $date_to)->result_array();
                $data['cosList'] = $this->studentfeemaster_model->getcos($date_from, $date_to)->result_array();
                $data['supplierList'] = $this->studentfeemaster_model->getAllsupliers($date_from, $date_to)->result_array();
                $data['gl_expenseList'] = $this->studentfeemaster_model->getAllexpenses($date_from, $date_to)->result_array();

                // Fetch retained earnings data (original _upto fields maintained)
                $data['feeList1'] = $this->studentfeemaster_model->getFeesummary_upto($date_from);
                $data['customerIncomeList1'] = $this->studentfeemaster_model->customer_income_upto($date_from)->result_array();
                $data['feediscount1'] = $this->studentfeemaster_model->getFeeBetweenDateCurrency_upto($date_from);
                $data['journalList1'] = $this->studentfeemaster_model->getAlljournals_upto($date_from)->result_array();
                $data['uniformList1'] = $this->studentfeemaster_model->getAlluniforms_upto($date_from)->result_array();
                $data['cosList1'] = $this->studentfeemaster_model->getcos_upto($date_from)->result_array();
                $data['supplierList1'] = $this->studentfeemaster_model->getAllsupliers_upto($date_from)->result_array();
                $data['gl_expenseList1'] = $this->studentfeemaster_model->getAllexpenses_upto($date_from)->result_array();

                // Calculate profits using helper function
                $data['net_profit'] = $this->calculate_net_profit(
                    $data['feeList'],
                    $data['customerIncomeList'],
                    $data['feediscount'],
                    $data['journalList'],
                    $data['uniformList'],
                    $data['cosList'],
                    $data['supplierList'],
                    $data['gl_expenseList']
                );

                $data['retained_earnings'] = $this->calculate_net_profit(
                    $data['feeList1'],
                    $data['customerIncomeList1'],
                    $data['feediscount1'],
                    $data['journalList1'],
                    $data['uniformList1'],
                    $data['cosList1'],
                    $data['supplierList1'],
                    $data['gl_expenseList1']
                );

                // Maintain original asset calculations
                $gl_assets_query = $this->studentfeemaster_model->getAllassets($date_from, $date_to);
                $data['assetList'] = $gl_assets_query->result_array();

                $other_assets_q = $this->studentfeemaster_model->getOtherassets($date_from, $date_to);
                $data['otherasset'] = $other_assets_q->result_array();

                // Maintain original other assets total calculation
                $total_other = 0.00;
                foreach ($data['otherasset'] as $a) {
                    $total_other += floatval($a['purchase_price']);
                }
                $data['total_other_assets'] = $total_other;

                // Maintain original settings and date values
                $data['settinglist'] = $this->setting_model->get();
                $data['settinglist1'] = $this->setting_model->get();
                $data['date_from2'] = $date_from;
                $data['date_to2'] = $date_to;
                $data['exp_title'] = 'Total Invoices From ' . $this->input->post('date_from') . " To " . $this->input->post('date_to');
            }
        }

        $this->load->view('layout/header', $data);
        $this->load->view('admin/financialreport/balanceshe', $data);
        $this->load->view('layout/footer', $data);
    }


public function printbalancesheet() {
    // Set menu context
    $this->session->set_userdata('top_menu', 'Financial Reports');
    $this->session->set_userdata('sub_menu', 'balancesheet/searchbalancesheet');

    // Load settings and payment modes
    $data['settinglist']   = $this->setting_model->get();
    $data['payment_modes'] = $this->payment_methods_model->select();

    // Determine report type and date range
    $data['report_type'] = $this->input->post('report_type') ?? 'summary';
    $date_from = date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('date_from')));
    $date_to   = date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('date_to')));

    // Title and date labels
    $data['exp_title']  = 'Total Invoices From ' . $this->input->post('date_from') . ' To ' . $this->input->post('date_to');
    $data['date_from2'] = $date_from;
    $data['date_to2']   = $date_to;

    // Currency symbol
    $data['currency_symbol'] = $this->customlib->getSchoolCurrencyFormat();

    // Fetch current period data
    $data['feeList']            = $this->studentfeemaster_model->getFeesummary($date_from, $date_to);
    $data['customerIncomeList'] = $this->studentfeemaster_model->customer_income($date_from, $date_to)->result_array();
    $data['feediscount']        = $this->studentfeemaster_model->getFeeBetweenDate($date_from, $date_to);
    $data['journalList']        = $this->studentfeemaster_model->getAlljournals($date_from, $date_to)->result_array();
    $data['uniformList']        = $this->studentfeemaster_model->getAlluniforms($date_from, $date_to)->result_array();
    $data['cosList']            = $this->studentfeemaster_model->getcos($date_from, $date_to)->result_array();
    $data['supplierList']       = $this->studentfeemaster_model->getAllsupliers($date_from, $date_to)->result_array();
    $data['gl_expenseList']     = $this->studentfeemaster_model->getAllexpenses($date_from, $date_to)->result_array();
    $data['assetList']          = $this->studentfeemaster_model->getAllassets($date_from, $date_to)->result_array();
    $data['otherasset']         = $this->studentfeemaster_model->getOtherassets($date_from, $date_to)->result_array();

    // Compute total other assets
    $total_other = 0.00;
    foreach ($data['otherasset'] as $asset) {
        $total_other += floatval($asset['purchase_price']);
    }
    $data['total_other_assets'] = $total_other;

    // -------------------- Retained Earnings (upto date_from) --------------------
    $data['feeList1']            = $this->studentfeemaster_model->getFeesummary_upto($date_from);
    $data['customerIncomeList1'] = $this->studentfeemaster_model->customer_income_upto($date_from)->result_array();
    $data['feediscount1']        = $this->studentfeemaster_model->getFeeBetweenDateCurrency_upto($date_from);
    $data['journalList1']        = $this->studentfeemaster_model->getAlljournals_upto($date_from)->result_array();
    $data['uniformList1']        = $this->studentfeemaster_model->getAlluniforms_upto($date_from)->result_array();
    $data['cosList1']            = $this->studentfeemaster_model->getcos_upto($date_from)->result_array();
    $data['supplierList1']       = $this->studentfeemaster_model->getAllsupliers_upto($date_from)->result_array();
    $data['gl_expenseList1']     = $this->studentfeemaster_model->getAllexpenses_upto($date_from)->result_array();
    $data['settinglist1']        = $this->setting_model->get();

    // -------------------- Net Profit Calculations --------------------
    $data['net_profit'] = $this->calculate_net_profit(
        $data['feeList'],
        $data['customerIncomeList'],
        $data['feediscount'],
        $data['journalList'],
        $data['uniformList'],
        $data['cosList'],
        $data['supplierList'],
        $data['gl_expenseList']
    );

    $data['retained_earnings'] = $this->calculate_net_profit(
        $data['feeList1'],
        $data['customerIncomeList1'],
        $data['feediscount1'],
        $data['journalList1'],
        $data['uniformList1'],
        $data['cosList1'],
        $data['supplierList1'],
        $data['gl_expenseList1']
    );

    // Load print view
    $this->load->view('print/printBalancesheet', $data);
}

   
}

?>