<?php
require_once '../../../resources/base_path_include.php';

require_once $base_path_to_resources . "includes/config.php"; // use require for mandatory files
require_once $base_path_to_resources . 'lib/function.php';
require_once $base_path_to_resources . 'lib/export/pdf/book_template/template_1/header.php';
require_once $base_path . "vendor/autoload.php";

require_once $base_path . 'modules/accounting/groups_ledgers/functions/ledger_functions.php';
require_once $base_path . 'modules/accounting/functions/basic_balance_function.php';
require_once $base_path_to_resources . 'lib/bucket_functions/bucket_functions.php';

require_once $base_path_to_resources . 'includes/aws_bucket_config.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

use \Spipu\Html2Pdf\Html2Pdf;
use \Spipu\Html2Pdf\Exception\Html2PdfException;
use \Spipu\Html2Pdf\Exception\ExceptionFormatter;


$ledgerFields = array(
    'ledger_name' => 'Name',

    'ledger_address' => 'Address',
    'ledger_pan' => 'Pan',
    'mobile' => 'Mobile',
    'email' => 'Email',
    'ledger_main_ledgerhead' => 'Parent Group',
    'ledger_opening_bal' => 'Opening Balance',
    'ledger_current_bal' => 'Current Balance',
);

$data = getLedger($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $search_string, $limit, $offset, $additionaldata);
// print_r($data['ledger_info']);
$ledgers = $data['ledger_info'];
$fields_to_remove = ['id'];

$ledgers = removeKeys($ledgers, $fields_to_remove);



$values = getArrayValues($ledgers);

$keys = getArrayKeys($ledgers[0]);
$formattedKeys = getArrayKeys($ledgers[0]);

foreach ($keys as $index => $k) {
    $formattedKeys[$index] = getCorrespondingValue($ledgerFields, $k);
}
// return array of keys and values
//print_r(array("values" => $values,"keys" => $formattedKeys));
$data = array("values" => $values, "keys" => $formattedKeys);
createPdf($data, $specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $function_code);



function createTable($keys, $values, $specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id)
{
    $book_info = GetBasicBook($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id);
    $currencySystem = $book_info['book_basic_info']['currency_format'];
    $number_of_decimal_places = $book_info['book_basic_info']['number_of_decimal_places'];
    $base_currency_symbol = $book_info['book_basic_info']['base_currency_symbol'];
    $count = 1;

    $thead = '<tr>';
    $thead .= '<th>Sr. No.</th>';
    foreach ($keys as $item) {
        $thead .= '
            <th>' . $item . '</th>
        ';
    }
    $thead .= '</tr>';
    $tbody = '';
    foreach ($values as $v) {
        $tbody .= '<tr >';
        $tbody .= '<td>' . $count++ . '</td>';

        foreach ($v as $item) {
            // Check if it's the 'Current Balance' or 'Opening Balance' column
            if (is_numeric($item)) { // Check if the item is a numeric value (assumed to be an amount)
                // Apply right alignment to the amount columns
                $tbody .= '<td style="text-align: right;font-family: Arial;">' . displayAmount($item, $currencySystem, $number_of_decimal_places, null) . '</td>';
            } else {
                $tbody .= '<td style="font-family: calibri;>' . $item . '</td>';
            }
        }
        $tbody .= '</tr>';
    }

    $table = '
    <table style="width: 100%; border-collapse: collapse;" border="1" cellspacing="10" cellpadding="5">
        <thead>
            ' . $thead . '
        </thead>
        <tbody>
            ' . $tbody . '
        </tbody>
    </table>';




    // print_r($table);die();
    return $table;
}

// <div maxwidth: 100%;> <div width:100%><table width 100></table></div>


function createPdf($data, $specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $function_code)
{

    $table = createTable($data['keys'], $data['values'], $specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id);

    $book_info = GetBasicBook($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id);
    $sql = "SELECT * FROM act_book_settings WHERE workspace_id = ? AND company_id = ? AND branch_id = ? AND book_id = ?";
    $stmt = $specific_db_conn->prepare($sql);
    $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id));
    $result = $stmt->fetchAll();
    // print_R($result);
    if (count($result) == 1) {

        $report_print_company_name = $result[0]['report_print_company_name'];
        $report_print_branch_name = $result[0]['report_print_branch_name'];
         $report_print_book_name = $result[0]['report_print_book_name'];
        $logo = $result[0]['logo'];
        $print_logo_bool = $result[0]['print_logo_bool'];
        if ($result[0]['logo'] !=  null and $print_logo_bool == 1) {
           $keyName = $logo;
            $file = displayFileFromS3($GLOBALS['s3_finware_bucket'], $GLOBALS['finware_bucketName'], $keyName);
        } else {

            $file =  null;
        }

        // print_R($file);
        if ($report_print_company_name == 1) {
            $company_name = $book_info['book_basic_info']['company_name'];
        } else {

            $company_name =  null;
        }

        if ($report_print_branch_name == 1) {
            $branch_name = $book_info['book_basic_info']['branch_name'];
        } else {

            $branch_name =  null;
        }
        if ($report_print_book_name == 1) {

            $book_name = $book_info['book_basic_info']['book_name'];
            $book_opening_date = $book_info['book_basic_info']['book_opening_date'];
            $book_closing_date = $book_info['book_basic_info']['book_closing_date'];
        } else {

            $book_name =  null;
            $book_opening_date =  null;
            $book_closing_date =  null;
        }
    } else {
        errorreturn('Branch or company not found.');
    }

    try {
        ob_start();
        // Your HTML content and PHP code here
        $html = ob_get_clean();
        $html2pdf = new Html2Pdf('P', 'A4', 'fr');
        $html2pdf->pdf->SetMargins(0, 0, 0);
        $html2pdf->pdf->SetDisplayMode('fullpage');
        $html2pdf->setDefaultFont('Arial');

        $book_template = createHeaderTemplate($specific_db_conn, $book_name, $company_name, $branch_name, $book_opening_date, $book_closing_date, $report_print_company_name, $report_print_branch_name, $report_print_book_name, $file, $function_code);

        $html = '
                
            
       
           <div style="width:100%;margin-top:20px">
            ' . $book_template . '
                ' . $table . '
           </div> ';
        // print_r($html);die();

        $html2pdf->WriteHTML($html); // in $content you put your content to have in pdf
        $html2pdf->Output('Ledger Report - Rejoice Finware.pdf');
    } catch (Html2PdfException $e) {
        $html2pdf->clean();
        $formatter = new ExceptionFormatter($e);
        echo $formatter->getHtmlMessage();
    }
}
