<?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';

$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();
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;


if (
    !checkIfIssetAndNotEmpty($postdata['company_id']) && !checkIfIssetAndNotEmpty($postdata['branch_id']) &&  !checkIfIssetAndNotEmpty($postdata['book_id']) && !checkIfIssetAndNotEmpty($postdata['ledger_name'])   && !checkIfIssetAndNotEmpty($postdata['ledger_opening_bal']) && !checkIfIssetAndNotEmpty($postdata['ledger_parent_group'])  && !checkIfIssetAndNotEmpty($postdata['ledger_main_ledgerhead'])
) {
    errorreturn("All * fields are required.");
}

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

$book_id = trim($postdata['book_id']);
$unique_id = $postdata['unique_id'];
$date = ($postdata['date']);
$ledgerid = $postdata['ledgerid'];
$name = $postdata['name'];
$address_ln_1 = $postdata['address_ln_1'];
$address_ln_2 = (isset($postdata['address_ln_2']) and !empty($postdata['address_ln_2'])) ? trim($postdata['address_ln_2']) : null;
$state_id = $postdata['state_id'];
$country_id = $postdata['country_id'];
$ledger_gst = $postdata['ledger_gst'];
$mobile = $postdata['mobile'];
$email = $postdata['email'];

$book_info = GetBasicBook($conn, $workspace_id, $company_id, $branch_id, $book_id);
$book_opening_date = $book_info['book_basic_info']['book_opening_date'];

if (!BranchGstValidation($ledger_gst)) { // for english chars + numbers only
    //eg House Name, Street Name
    errorreturn('Invalid Ledger GST Number');
}

//Branch GST 
if (!CheckAddressValidation($address_ln_1)) {
    //eg House Name, Street Name
    errorreturn('Invalid Address');
}


if (strlen($mobile) != 13 or $mobile <= 0) {
    errorreturn('Enter valid 12 digit mobile number ' . $mobile);
}

if (!CheckEMailIsValidOrNot($email)) {
    errorreturn('Enter valid Email Id');
}

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

    $function_code = 'create_ledger'; // uses function code create_ledgers

    $confirmed_role_user = validatePrimaryAccess($conn, $workspace_id, $company_id, $branch_id, null, $role, $userid, $function_code, ['superadmin', 'admin', null]);
    if ($confirmed_role_user['status'] != true) errorreturn($confirmed_role_user['errormsg']);

    // email and password validation
    $sql = "SELECT ledger_gst,mobile,email FROM  act_ledger_addresses WHERE (ledger_gst = ?";
    $array_param = [$ledger_gst];
    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 = $conn->prepare($sql);
    $res->execute($array_param);
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("GST / Email / Mobile already exists");
    }

    try {

        // insert query of stock transaction 
        $sql = "INSERT INTO   act_ledger_addresses(workspace_id, company_id, branch_id, book_id,date,ledgerid,name,address_ln_1,address_ln_2,state_id,country_id,ledger_gst,mobile,email)
                VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt =  $conn->prepare($sql);
        $stmt->execute(array($workspace_id, $company_id, $branch_id, $book_id, $date, $ledgerid, $name, $address_ln_1, $address_ln_2, $state_id, $country_id, $ledger_gst, $mobile, $email));
        $id = $conn->lastInsertId();
        $ledgerid = $conn->lastInsertId();


        successreturn(array('id' => $ledgerid, 'successmsg' => "Ledger Addresses added successfully."));
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }
} else if (
    $postdata['function_type'] == "alter_ledger_addresses" and checkIfIssetAndNotEmpty($postdata['ledgerid']) and checkIfIssetAndNotEmpty($workspace_id) and checkIfIssetAndNotEmpty($postdata['company_id'])
    and checkIfIssetAndNotEmpty($postdata['book_id']) and checkIfIssetAndNotEmpty($postdata['branch_id'])
) {


    $id = $postdata['address_id'];
    $function_code = 'alter_ledger'; // uses function code alter_ledgers

    $confirmed_role_user = validatePrimaryAccess($conn, $workspace_id, $company_id, $branch_id, null, $role, $userid, $function_code, ['superadmin', 'admin', null]);
    if ($confirmed_role_user['status'] != true) errorreturn($confirmed_role_user['errormsg']);

    // email and password validation
    $sql = "SELECT ledger_gst,mobile,email FROM  act_ledger_addresses WHERE id != ? and workspace_id  =? and company_id =? and branch_id =? and book_id =? and (ledger_gst = ? or email = ? and mobile =?)";
    $res = $conn->prepare($sql);
    $res->execute(array($id, $workspace_id, $company_id, $branch_id, $book_id, $ledger_gst, $email, $mobile));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("GST / Email / Mobile already exists");
    }


    $sql = "UPDATE act_ledger_addresses SET date=?,ledgerid=?,name=?,address_ln_1=?,address_ln_2=?,state_id=?,country_id=?,ledger_gst=?,mobile=?,email=? WHERE id=? and workspace_id  =? and company_id =? and branch_id =? and book_id =? ";
    $conn->prepare($sql)->execute(array(
        $date, $ledgerid, $name, $address_ln_1, $address_ln_2, $state_id, $country_id, $ledger_gst, $mobile, $email, $id, $workspace_id, $company_id, $branch_id, $book_id
    ));
    successreturn("Updated details Successfully");
}
