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

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/currency_functions.php";
require_once $base_path_to_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_resources . 'lib/validate_function.php';


//valdation file

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

require_once $base_path . 'modules/accounting/groups_ledgers/functions/group_functions.php';
//valdation file
require_once $base_path . 'modules/accounting/functions/basic_balance_function.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/groups_ledgers/functions/params_functions.php';
require_once $base_path . 'modules/accounting/groups_ledgers/functions/ledger_functions.php';
//creating dynamic db
require_once $base_path_to_resources . 'includes/specific_db_config.php';
$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['company_id']) or !checkIfIssetAndNotEmpty($postdata['company_id']) or
    !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
    !isset($postdata['book_id']) or !checkIfIssetAndNotEmpty($postdata['book_id']) or
    !isset($postdata['ledger_name']) or !checkIfIssetAndNotEmpty($postdata['ledger_name'])   or
    !isset($postdata['ledger_opening_bal']) or !checkIfIssetAndNotEmpty($postdata['ledger_opening_bal']) or
    !isset($postdata['ledger_parent_group']) or !checkIfIssetAndNotEmpty($postdata['ledger_parent_group'])
    or !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['jwt_token']) or !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}


validateApiSignature($postdata['api_signature']);

//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;
$created_by = $jwt_validate->data->username;




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

require_once $base_path . 'modules/accounting/book_management/basic_book_info_function.php';
$book_id = trim($postdata['book_id']);
$function_code = $postdata['function_type'];
$confirmed_role_user = validatePrimaryAccess($conn, $workspace_id, $role, $userid, ['superadmin', 'admin', null]);
if (!$confirmed_role_user) {
    errorreturn('Access denied.');
} else {
    $specific_db_conn = dynamicDbConnection($confirmed_role_user);
    if ($role == null) {
        checkCompanyBranchFunctionAccess($specific_db_conn, $role, $userid, $workspace_id, $company_id, $branch_id, $book_id,  $function_code);
    }
}


$ledger_name = ucwords(trim($postdata['ledger_name']));
$ledger_pan = (isset($postdata['ledger_pan']) and !empty($postdata['ledger_pan'])) ? strtoupper(trim($postdata['ledger_pan'])) : null;
$ledger_gst = (isset($postdata['ledger_gst']) and !empty($postdata['ledger_gst'])) ? strtoupper(trim($postdata['ledger_gst'])) : null;
$mobile = (isset($postdata['mobile']) and !empty($postdata['mobile'])) ? trim($postdata['mobile']) : null;
$email = (isset($postdata['email']) and !empty($postdata['email'])) ? strtolower(trim($postdata['email'])) : null;
$balancetype = (isset($postdata['balancetype']) and !empty($postdata['balancetype'])) ? trim($postdata['balancetype']) : null;
$ledger_opening_bal = floatval(trim($postdata['ledger_opening_bal'])); // ledger_opening_bal
// ledger_opening_balancetype -cr/dr
$ledger_opening_bal = relativeBalance($ledger_opening_bal, $balancetype);
$ledger_parent_group = trim($postdata['ledger_parent_group']);
$param_1 = (isset($postdata['param_1']) and !empty($postdata['param_1'])) ? trim($postdata['param_1']) : null;
$param_2 = (isset($postdata['param_2']) and !empty($postdata['param_2'])) ? trim($postdata['param_2']) : null;
$tax_type = (isset($postdata['tax_type']) and !empty($postdata['tax_type'])) ? trim($postdata['tax_type']) : null;
$sub_type = (isset($postdata['sub_type']) and !empty($postdata['sub_type'])) ? trim($postdata['sub_type']) : null;
$pincode_ledger = (isset($postdata['pincode']) and !empty($postdata['pincode'])) ? trim($postdata['pincode']) : null;
$date_created = date('Y-m-d');
$addresses = (isset($postdata['addresses']) and !empty($postdata['addresses'])) ? $postdata['addresses'] : null;

$tax_types = ['GST', 'Others'];
$sub_types = ['CGST', 'SGST', 'IGST', 'CESS'];

if ($ledger_parent_group === 'Duties & Taxes') {
    if (!in_array($tax_type, $tax_types) and !empty($tax_type)) {
        errorreturn("Tax type is required and must be one of: GST, Others");
    }

    if ($tax_type === 'GST' and !in_array($sub_type, $sub_types)) {
        errorreturn("Sub type is required for GST and must be one of: CGST, SGST, IGST, CESS");
    }
}
if($pincode_ledger != null){
if (!PinCodeValidation($pincode_ledger)) { // 6 digit only
        //eg House Name, Street Name
        errorreturn('Invalid Pin Code');
}
}



$book_info = GetBasicBook($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id);
$book_opening_date = $book_info['book_basic_info']['book_opening_date'];
// check address array
if ($addresses != null and is_array($addresses)) {
    foreach ($addresses as $data) {
        $name = ucwords(trim($data['name'])); // should be ucwords mandatory
        $address_ln_1 = ucwords(trim($data['address_ln_1'])); // ucwords and mandatory
        $address_ln_2 = (isset($data['address_ln_2']) and !empty($data['address_ln_2'])) ? ucwords(trim($data['address_ln_2'])) : null;  // ucwords NOT mandatory can be null
        $state_id = $data['state_id']; // mandatory also to be validated from the list we have
        $country_id = $data['country_id']; // mandatory also to be validated from the list we have
        $postal_code = (isset($data['postal_code']) and !empty($data['postal_code'])) ? $data['postal_code'] : null;
        $ledger_gst = (isset($data['ledger_gst']) and !empty($data['ledger_gst'])) ? $data['ledger_gst'] : null; // NOT MANDATORY to be validated if received from regex of gst
        $email = (isset($data['email']) and !empty($data['email'])) ? $data['email'] : null;
        $mobile = (isset($data['mobile']) and !empty($data['mobile'])) ? $data['mobile'] : null;
        $pincode = (isset($data['pincode']) and !empty($data['pincode'])) ? $data['pincode'] : null; 

        if ((isset($data['function']) and $data['function'] != 'delete')) {
            $sql_country = "SELECT * FROM country_info WHERE id = ?";
            $stmt_country = $conn->prepare($sql_country);
            $stmt_country->execute(array($country_id));
            $result_country = $stmt_country->fetchAll();
            if (count($result_country) < 1) {
                errorreturn("Country not found.");
            }
            //validate country id
            $sql_state = "SELECT * FROM state_info WHERE id = ? and country_id =?";
            $stmt_state = $conn->prepare($sql_state);
            $stmt_state->execute(array($state_id, $country_id));
            $result_state = $stmt_state->fetchAll();
            if (count($result_state) < 1) {
                errorreturn("State not found.");
            }
            if (empty($address_ln_1)) {
                // Address line 1 is empty
                errorreturn("Address Line 1 is required."); // You can handle the validation error here
            }

            if (!CheckAddressValidation($address_ln_1)) {
                //eg House Name, Street Name
                errorreturn('Invalid Address' . $address_ln_1);
            }
            if ($address_ln_2 != null) {
                if (!CheckAddressValidation($address_ln_2)) {
                    //eg House Name, Street Name
                    errorreturn('Invalid Address' . $address_ln_2);
                }
            }
            if ($email != null) {
                if (!CheckEMailIsValidOrNot($email)) {
                    errorreturn('Enter valid Email Id');
                }
            }
            if ($ledger_gst != null) {
                if (!BranchGstValidation($ledger_gst)) { // for english chars + numbers only
                    //eg House Name, Street Name
                    errorreturn('Invalid GST Number');
                }
            }
            if ($mobile != null) {
                if (strlen($mobile) != 13 or $mobile <= 0) {
                    errorreturn('Enter valid 12 digit mobile number ' . $mobile);
                }
            }
            
            if($pincode != null){
            if (!PinCodeValidation($pincode)) { // 6 digit only
                //eg House Name, Street Name
                errorreturn('Invalid Pin Code');
             }
            }
        }
    }
}

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


    // email and password validation
    $sql = "SELECT ledger_name,mobile,email FROM act_ledgerdetails WHERE (ledger_name = ?";
    $array_param = [$ledger_name];
    if ($email != '' and !empty($email)) {
        $sql = $sql . ' or email = ?';
        $array_param[] = $email;
    }
    if ($mobile != '' and !empty($mobile)) {
        $sql = $sql . ' or email = ?';
        $array_param[] = $mobile;
    }

    $sql = $sql . ") and workspace_id  =? and company_id =? and branch_id =? and book_id =?";
    $array_param[] = $workspace_id;
    $array_param[] = $company_id;
    $array_param[] = $branch_id;
    $array_param[] = $book_id;
    $res = $specific_db_conn->prepare($sql);
    $res->execute($array_param);
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("Name / Email / Mobile already exists");
    }

    //leder pan and gst validation
    $sql = "SELECT ledger_name,ledger_pan,ledger_gst FROM act_ledgerdetails WHERE (ledger_pan = ?";
    $array_param = [$ledger_pan];
    if ($ledger_pan != '' and !empty($ledger_pan)) {
        $sql = $sql . ' or ledger_pan = ?';
        $array_param[] = $ledger_pan;
    }
    if ($ledger_gst != '' and !empty($ledger_gst)) {
        $sql = $sql . ' or ledger_gst = ?';
        $array_param[] = $ledger_gst;
    }
    $sql = $sql . ") and workspace_id  =? and company_id =? and branch_id =? and book_id =?";
    $array_param[] = $workspace_id;
    $array_param[] = $company_id;
    $array_param[] = $branch_id;
    $array_param[] = $book_id;
    $res = $specific_db_conn->prepare($sql);
    $res->execute($array_param);
    $result_ledger = $res->fetchAll();
    if (count($result_ledger) >= 1) {
        errorreturn("Leder Pan and GST already exists in Ledger");
    }

    try {

        // echo $main_ledgerhead;die();
        $sql1 = "Select ledgerhead_name from  act_ledgerheads_basic where ledgerhead_name = ?";
        $stmt = $conn->prepare($sql1);
        $stmt->execute(array($ledger_parent_group));
        $result1 = $stmt->fetchAll();

        if (count($result1) == 1) {
            $ledger_main_ledgerhead = $ledger_parent_group;
        } else {

            $sql1 = "Select group_name,main_ledgerhead from act_group_info where group_name = ? and workspace_id  =? and company_id =? and branch_id =? and book_id =?  ";
            $stmt = $specific_db_conn->prepare($sql1);
            $stmt->execute(array($ledger_parent_group, $workspace_id, $company_id, $branch_id, $book_id));
            $result1 = $stmt->fetchAll();
            if (count($result1) != 1) {
                errorreturn('Parent group does not exist.');
            }
            foreach ($result1 as $row1) {
                $ledger_main_ledgerhead = $row1['main_ledgerhead'];
            }
        }

        // include the file that validates param
        $validateparam = ValidateParam($ledger_main_ledgerhead, $param_1);

        // validating if taxtype, subtype can be used
        if ($ledger_main_ledgerhead != 'Duties & Taxes') {
            $tax_type = null;
            $sub_type = null;
        }

        $sql = "INSERT INTO act_ledgerdetails(workspace_id,company_id,branch_id,book_id,ledger_name,ledger_pan,ledger_gst,mobile,email,ledger_opening_bal,ledger_current_bal,
        ledger_parent_group,ledger_main_ledgerhead,date_created,time_created,created_by,param_1,param_2,tax_type,sub_type,pincode,status)
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt =  $specific_db_conn->prepare($sql);
        $stmt->execute(array(
            $workspace_id, $company_id, $branch_id, $book_id, $ledger_name, $ledger_pan, $ledger_gst, $mobile, $email, $ledger_opening_bal, 0.00,
            $ledger_parent_group, $ledger_main_ledgerhead, $date_created, time(), $created_by, $validateparam, $param_2, $tax_type, $sub_type,$pincode_ledger,'1'
        ));

        $ledgerid = $specific_db_conn->lastInsertId();

        UpdateLedgerBalance($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $ledgerid, $ledger_opening_bal, $book_opening_date, $ledger_main_ledgerhead, $ledger_parent_group);

        if ($addresses != null and is_array($addresses)) {

            InsertLedgerAddress($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $ledgerid, $addresses);
        } else {

            $addresses = null;
        }



        successreturn(array('ledger_id' => $ledgerid, 'successmsg' => "Ledger added successfully."));
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }
} else if ($postdata['function_type'] == "alter_ledger") {

    if (!isset($postdata['ledgerid']) or !checkIfIssetAndNotEmpty($postdata['ledgerid'])) {
        errorreturn('Error in updating the ledger.');
    } else {
        $id = $postdata['ledgerid'];
    }


    $function_code = $postdata['function_type'];
    $confirmed_role_user = validatePrimaryAccess($conn, $workspace_id, $role, $userid, ['superadmin', 'admin', null]);
    if (!$confirmed_role_user) {
        errorreturn('Access denied.');
    } else {
        $specific_db_conn = dynamicDbConnection($confirmed_role_user);
        if ($role == null) {
            checkCompanyBranchFunctionAccess($specific_db_conn, $role, $userid, $workspace_id, $company_id, $branch_id, $book_id,  $function_code);
        }
    }

    $sql = "SELECT ledger_name,mobile,email FROM act_ledgerdetails WHERE id != ? and workspace_id  =? and company_id =? and branch_id =? and book_id =? and (ledger_name = ? or email = ? and mobile =?)";
    $res = $specific_db_conn->prepare($sql);
    $res->execute(array($id, $workspace_id, $company_id, $branch_id, $book_id, $ledger_name, $email, $mobile));

    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("Name / Email / Mobile already exists");
    }

    $sql_count = "SELECT ledger_pan,ledger_gst FROM act_ledgerdetails WHERE id != ? and workspace_id  =? and company_id =? and branch_id =? and book_id =? and (ledger_pan = ? or ledger_gst = ?)";
    $res_ledger = $specific_db_conn->prepare($sql_count);
    $res_ledger->execute(array($id, $workspace_id, $company_id, $branch_id, $book_id, $ledger_pan, $ledger_gst));

    $result_ledger = $res_ledger->fetchAll();
    if (count($result_ledger) >= 1) {
        errorreturn("ledger GST / Pan  already exists");
    }

    // check addresses data
    if ($addresses != null and is_array($addresses)) {
        foreach ($addresses as $temp) {
            $address_id = (isset($temp['id']) and !empty($temp['id'])) ? $temp['id'] : null;
            if ($address_id != null) {
                $sql_transactiondata = "SELECT count(*) as total FROM act_transactiondata WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and shipping_address = ? or billing_address = ? ";
                $stmt_transactiondata = $specific_db_conn->prepare($sql_transactiondata);
                $stmt_transactiondata->execute(array($workspace_id, $company_id, $branch_id, $book_id, $address_id, $address_id));
                $result_transactiondata = $stmt_transactiondata->fetchAll();
                if ($result_transactiondata[0]['total'] >= 1) {

                    errorreturn("Unable to delete/update Ledger address because of the presence in transaction data.");
                }
            }
        }
    }


    $res = $specific_db_conn->prepare("SELECT ledger_opening_bal,ledger_main_ledgerhead,ledger_parent_group FROM act_ledgerdetails WHERE id = ? and  workspace_id  =? and company_id= ? and book_id =? and branch_id =?");
    $res->execute(array($id, $workspace_id, $company_id, $book_id, $branch_id));
    $result1 = $res->fetchAll();

    $existing_openingbal = $result1[0]['ledger_opening_bal'];
    $ledger_mainledgerhead = $result1[0]['ledger_main_ledgerhead'];
    $ledger_parentgroup = $result1[0]['ledger_parent_group'];


    $diff = getRelativeDifference($ledger_opening_bal, $existing_openingbal);


    if ($diff != 0) {
        UpdateLedgerBalance($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $id, $diff, $book_opening_date, $ledger_mainledgerhead, $ledger_parentgroup);
    }


    // echo $main_ledgerhead;die();
    $sql1 = "Select ledgerhead_name from  act_ledgerheads_basic where ledgerhead_name = ?";
    $stmt = $conn->prepare($sql1);
    $stmt->execute(array($ledger_parent_group));
    $result1 = $stmt->fetchAll();

    if (count($result1) == 1) {
        $ledger_main_ledgerhead = $ledger_parent_group;
    } else {

        $sql1 = "Select group_name,main_ledgerhead from act_group_info where group_name = ? and workspace_id  =? and company_id =? and branch_id =? and book_id =?  ";
        $stmt = $specific_db_conn->prepare($sql1);
        $stmt->execute(array($ledger_parent_group, $workspace_id, $company_id, $branch_id, $book_id));
        $result1 = $stmt->fetchAll();
        if (count($result1) != 1) {
            errorreturn('Parent group does not exist.');
        }
        foreach ($result1 as $row1) {
            $ledger_main_ledgerhead = $row1['main_ledgerhead'];
        }
    }



    if ($ledger_main_ledgerhead == 'Profit & Loss Account') {
        errorreturn("Contact admin.");
    } else {
        // include the file that validates param
        $validateparam = ValidateParam($ledger_main_ledgerhead, $param_1);

        // validating if taxtype, subtype can be used
        if ($ledger_main_ledgerhead != 'Duties & Taxes') {
            $tax_type = null;
            $sub_type = null;
        }

        $sql = "UPDATE act_ledgerdetails SET ledger_name=?, ledger_pan=?,ledger_gst=?,mobile=?,email=?,ledger_opening_bal =?,
    ledger_parent_group=? , ledger_main_ledgerhead =?, param_1 =?,param_2 = ?,tax_type=?,sub_type=?,pincode = ? WHERE id=? and workspace_id  =? and company_id =? and branch_id =? and book_id =? ";
        $specific_db_conn->prepare($sql)->execute(array(
            $ledger_name, $ledger_pan, $ledger_gst, $mobile, $email, $ledger_opening_bal,
            $ledger_parent_group, $ledger_main_ledgerhead, $validateparam, $param_2, $tax_type, $sub_type,$pincode_ledger, $id, $workspace_id, $company_id, $branch_id, $book_id
        ));


        if ($addresses != null and is_array($addresses)) {

            InsertLedgerAddress($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $id, $addresses);
        } else {

            $addresses = null;
        }



        successreturn("Updated ledger details Successfully");
    }
}
