<?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/print/book_template/template_1/header.php';
require_once $base_path . "vendor/autoload.php";
require_once $base_path_to_resources . "lib/currency_functions.php";

//valdation file
require_once $base_path . 'modules/accounting/stock_management/functions/stock_function.php';
require_once $base_path . 'modules/accounting/stock_management/inventory_regions/region_functions.php';
require_once $base_path . 'modules/accounting/book_management/basic_book_info_function.php';
require_once $base_path . 'modules/accounting/reports/valuation_methods/closing_stock_summary/fifo_summary_function.php';
require_once $base_path . 'modules/accounting/functions/basic_balance_function.php';

$ledgerFields = array('stock_name'=>'Name',
 "opening_stock">'Opening Stock',
     "opening_stock"=>'Opening Stock',
     "closing_stock"=>'Closing Stock',
     "current_balance"=>'Current Balance',
    'unit_name'=>'Unit Name',
    'opening_qty'=>'Opening Quantity',
    'opening_balance'=>'Opening Balance',
    'parent_group'=>'Parent Group',
    'filesattached'=>'Stock Image'
    );
    
    $additionaldata = array();
    $additionaldata = ['id', 'stock_name', 'current_qty'];
    $additionaldata = array_merge($additionaldata, $postdata['additional_data']);
    GetStockDetail($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $search_string, $additionaldata, $limit, null, $appended_region_bool,$book_opening_date,$book_closing_date);
    
     $data = GetStockDetail($specific_db_conn,$workspace_id,$company_id,$branch_id,$book_id, $search_string,$additionaldata,$limit,$offset,$page,null,$book_opening_date,$book_closing_date);
    // print_r($data['ledger_info']);
    $ledgers = $data['stock_info'];
    $fields_to_remove = ['id','barcode_match'];
    
    $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);
    
    createPrint($specific_db_conn,$data, $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'];
    //print_r($keys,$values);
    $count = 1;

    $thead = '<tr>';
    $thead .= '<th style="text-align:left">Sr. No.</th>';
    foreach ($keys as $item) {
         if ($item == 'Current Balance') { // Check if the item is a numeric value (assumed to be an amount)
            // Apply right alignment to the amount columns
            $thead .= '<th style="text-align: right;font-family:calibri">' . $item . '</th>';
        } else {
            $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: calibri">' . formatCurrency($item, $currencySystem, $number_of_decimal_places, null) . '</td>';
        } elseif (filter_var($item, FILTER_VALIDATE_URL) && getimagesize($item)) {
            // Check if the item is a valid URL and if it represents an image
            // Display image if it's a valid image URL
            $link = 'https://rejoicebilldesk.in/rjlbilldesk_development/';
            $tbody .= '<td><img src="' . $item . '" style="max-width: 50px; max-height: 50px;border-radius:50%;" /></td>';
        } else {
            // If the item is not numeric or an image URL, display it as regular text
            $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>';
    return $table;
}
function createPrint( $specific_db_conn,$data, $workspace_id, $company_id, $branch_id, $book_id,$function_code)
{
     $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) {
            if ($print_logo_bool == 1) {
                $link = 'https://rejoicebilldesk.in/rjlbilldesk_development/';

                $file = $link . $logo;
            }
        } else {

            $file =  null;
        }
        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.');
    }

     
   
     // create header for book
   $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);
     
     //generate table
     $table = createTable($data['keys'], $data['values'],$specific_db_conn,$workspace_id, $company_id, $branch_id, $book_id);
        
     // Initial HTML content
    $initialHtml = '<div>' . $book_template . '</div>
                   ';
    
    // Concatenate the table HTML with the initial HTML
    $html = '<div>' . $initialHtml . '<div>' . $table . '</div></div>';
    
    // Printing the generated HTML
    echo $html;
}
?>
