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

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

require_once $base_path_to_resources . "includes/config.php";
require_once $base_path_to_resources . 'lib/function.php';
require_once $base_path_to_resources . "lib/currency_functions.php";


//valdation file
require_once $base_path . 'user_management/authenticate.php';

//spreadsheet function
require_once $base_path . "vendor/autoload.php";


use PhpOffice\PhpSpreadsheet\IOFactory;

//valdation file
require_once $base_path . 'modules/accounting/groups_ledgers/functions/ledger_functions.php';
require_once $base_path . 'modules/accounting/book_management/basic_book_info_function.php';
require_once $base_path . 'modules/accounting/groups_ledgers/update_ledger_balance.php';
require_once $base_path . 'modules/accounting/functions/basic_balance_function.php';
//bank instrument
require_once $base_path . 'modules/accounting/transaction_management/functions/bank_instrument_functions.php';

//transactiontype validate
require_once $base_path . 'modules/accounting/transaction_management/functions/transactiontype_validation_functions.php';
require_once $base_path . 'modules/accounting/transaction_management/transaction_record_classification/transactiondata.php';

require_once $base_path . 'modules/accounting/stock_management/functions/stock_transaction_function.php';
//stock transaction classification
require_once $base_path . 'modules/accounting/stock_management/functions/stock_transaction_classification.php';
require_once $base_path . 'modules/accounting/stock_management/functions/stock_function.php';

$postdata = json_decode(file_get_contents("php://input"), true);

// //authenticate jwt token
// $jwttoken = $postdata['jwt_token'];
// $jwt_validate = authenticate_jwt($jwttoken);
// //then workspace_id is decoded in data of jwt use from there
// $userid = $jwt_validate->data->id;
// $workspace_id = $jwt_validate->data->workspace_id;
// $role = $jwt_validate->data->role;
// $username = $jwt_validate->data->username;
$company_id = '1';
$branch_id = '1';
$book_id = '1';
$workspace_id = '1';

function GetBasicLedgerNameDetail($conn, $ledger_name, $workspace_id, $company_id, $branch_id, $book_id, $additionaldata)
{
    $sql = "Select ";
    $array_counter = 0;
    foreach ($additionaldata as $column_name) {
        if ($array_counter == 0) {
            $sql = $sql . " " . $column_name;
        } else {
            $sql = $sql . ", " . $column_name;
        }
        $array_counter++;
    }

    $sql = $sql . " FROM  act_ledgerdetails WHERE  workspace_id = ? and company_id =? and branch_id =? and book_id  =? and ledger_name = ? ";

    $stmt = $conn->prepare($sql);
    $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledger_name));
    $result = $stmt->fetchAll();

    if (count($result) == 1) {
        $array_return = [];

        foreach ($additionaldata as $column_name) {
            $array_return[] = array('' . $column_name . '' => $result[0]['' . $column_name]);
        }

        return $array_return;
    } else {
        errorreturn("Ledgerid is not exists in ledgerdetail");
    }
}


//if ($postdata['function_type'] == "import_transaction") {

// $company_id = trim($postdata['company_id']);
// $branch_id = trim($postdata['branch_id']);
// $book_id = trim($postdata['book_id']);


$tmpFilePath = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size']; // File size in bytes
$fileExtension = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));

// Define an array of allowed file extensions
$allowedExtensions = array("xlsx", "xls", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

// Check if the uploaded file's extension is in the list of allowed extensions
if (!in_array($fileExtension, $allowedExtensions)) {
    errorreturn("Only XLSX and XLS files are allowed.");
}
$allData = array();
$maxFileSize = 10 * 1024 * 1024;  // 10 MB in bytes
// Check if the file size is within the limit
if ($fileSize <= $maxFileSize) {
    $spreadsheet = IOFactory::load($tmpFilePath);
    // Select the first worksheet
    $worksheet = $spreadsheet->getSheet(0);
    // $data = $worksheet->toArray();
    // Iterate through rows in pairs
    $rowIterator = $worksheet->getRowIterator();
    $twoRows = [];
    $rowCount = 0;
    foreach ($rowIterator as $rowNumber => $row) {

        // Check if the current row is the 7th row
        if ($rowNumber >= 7) {
            $cellIterator = $row->getCellIterator();
            $rowData = [];

            $index_cell = 1;  // this keeps a tab on columns in a row from A - G (1 - 7)

            foreach ($cellIterator as $cell) {
                $rowData[] = $cell->getValue();
                $index_cell++;
                if ($index_cell == 7) {
                    break;
                }
            }
            // Add the row's data to the $twoRows array
            $twoRows[] = $rowData;
            // Process every two rows
            if (count($twoRows) === 2) {
                 // Ensure we have two complete rows
                 if (count($twoRows[0]) === count($twoRows[1])) {
                foreach ($twoRows as $rowData) {
                    $serialDate = (isset($rowData[0]) and !empty($rowData[0])) ? $rowData[0] : null;
                    if (empty(trim($serialDate))) {
                        break;
                    }
                    $excelBaseDate = 25569; // Excel's base date is January 1, 1900
                    $unixTimestamp = ($serialDate - $excelBaseDate) * 86400; // Convert to Unix timestamp

                    $transaction_date = date('Y-m-d', $unixTimestamp);
                    $transactiontype = (isset($rowData[1]) and !empty($rowData[1])) ? ($rowData[1]) : null;
                    $transaction_number = (isset($rowData[2]) and !empty($rowData[2])) ? ($rowData[2]) : null;
                    $ledger_name = (isset($rowData[3]) and !empty($rowData[3])) ? ($rowData[3]) : null;
                    $dr_amount = isset($rowData[4]) ? $rowData[4] : null;
                    $cr_amount = isset($rowData[5]) ? $rowData[5] : null;
                    
                    $narration = (isset($rowData[6]) and !empty($rowData[6])) ? ucwords(trim($rowData[6])) : null;
                    $last_modified_by = null;
                    $filesattached = null;
                    $reference_number =  null;
                    $dispatch_id = null;
                    $billing_address = null;
                    $shipping_address = null;
                    $username = 'abc';
                    $userid = '1';
                  
                   
                   }
                    
                    if ($transactiontype== 'contra') {
                            //required file for stock transaction
                            require_once $base_path . 'modules/accounting/transaction_management/import/import_basic_transaction.php';
                        }
                 }
                        // Reset $twoRows for the next pair of rows
                        $twoRows = [];
                  
            }


            //print_r($insert_data);
        }
    }
} else {
    // File size exceeds the allowed limit
    errorreturn('File size exceeds the maximum allowed limit (10 MB).');
}
    
    
//}