<?php

ini_set('display_errors', 1);
// error_reporting(0);

//require_once '../../resources/base_path_include.php';
require_once '../../../resources/base_path_include.php';
// should we not call header and ch
require_once $base_path_to_resources . "includes/config.php"; // use require for mandatory files
//require($base_path_to_resources."/lib/function.php");
require_once $base_path_to_resources . 'lib/function.php';
require_once $base_path_to_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_resources . "lib/currency_functions.php";
require_once $base_path_to_resources . 'lib/validate_function.php';

//creating dynamic db
require_once $base_path_to_resources . 'includes/specific_db_config.php';

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


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


if (
    !isset($postdata['ledgerid']) or !checkIfIssetAndNotEmpty($postdata['ledgerid']) or !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['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type']) 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;
//print_r($workspace_id);die();
$role = $jwt_validate->data->role;
$username = $jwt_validate->data->username;

// either the user has to fill gst or pan or ledgerhead 
function deleteLedgerDetails($specific_db_conn, $ledgerid, $workspace_id, $company_id, $branch_id, $book_id)
{
     // Set the isolation level to READ COMMITTED
    $specific_db_conn->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");

    // Begin a transaction
    $specific_db_conn->beginTransaction();
    try {

    $sql_ledger = "SELECT ledger_main_ledgerhead, ledger_name FROM act_ledgerdetails WHERE id = ? AND workspace_id = ? AND company_id = ? AND branch_id = ? AND book_id = ?";
    $stmt_ledger = $specific_db_conn->prepare($sql_ledger);
    $stmt_ledger->execute(array($ledgerid, $workspace_id, $company_id, $branch_id, $book_id));
    $result_ledger = $stmt_ledger->fetchAll();

    if (count($result_ledger) == 1) {
        if ($result_ledger[0]['ledger_main_ledgerhead'] == 'Profit & Loss Account' and $result_ledger[0]['ledger_name'] == 'Profit & Loss A/c') {
            errorreturn("Profit & Loss A/c ledger cretaed by system cannot be deleted.");
        }
    }

    $sql_addresses = "SELECT id FROM act_ledger_addresses WHERE workspace_id = ? AND company_id = ? AND branch_id = ? AND book_id = ? and ledgerid = ?";
    $stmt_addresses = $specific_db_conn->prepare($sql_addresses);
    $stmt_addresses->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerid));
    $result_addresses = $stmt_addresses->fetchAll();

    if (count($result_addresses) >= 1) {
        foreach ($result_addresses as $address) {
            $addresses_id = $address['id'];

            // Check presence in transaction data
            $sql_transactionrecord = "SELECT count(*) as total FROM act_transactiondata WHERE workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and (billing_address = ? or shipping_address = ?)";
            $stmt_transactionrecord = $specific_db_conn->prepare($sql_transactionrecord);
            $stmt_transactionrecord->execute(array($workspace_id, $company_id, $branch_id, $book_id, $addresses_id, $addresses_id));
            $result_transactionrecord = $stmt_transactionrecord->fetchAll();
            if ($result_transactionrecord[0]['total'] >= 1) {
                errorreturn("Unable to delete Ledger address  because of its presence in transactions.");
            }
        }
    }
    $sql_transactionrecord = "SELECT count(*) as total FROM act_transactionrecord WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and ledgerid = ? ";
    $stmt_transactionrecord = $specific_db_conn->prepare($sql_transactionrecord);
    $stmt_transactionrecord->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerid));
    $result_transactionrecord = $stmt_transactionrecord->fetchAll();
    if ($result_transactionrecord[0]['total'] >= 1) {

        errorreturn("Unable to delete Ledgers because of the presence in transaction record.");
    }

    $sql_denominations = "SELECT count(*) as total FROM act_denominations WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and ledgerid = ? ";
    $stmt_denominations = $specific_db_conn->prepare($sql_denominations);
    $stmt_denominations->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerid));
    $result_denominations = $stmt_denominations->fetchAll();
    if ($result_denominations[0]['total'] >= 1) {

        errorreturn("Unable to delete Ledgers because of the presence in denominatoins.");
    }

    $sql_bankinstrument = "SELECT count(*) as total FROM act_bankinstrument WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and ledgerid = ? ";
    $stmt_bankinstrument = $specific_db_conn->prepare($sql_bankinstrument);
    $stmt_bankinstrument->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerid));
    $result_bankinstrument = $stmt_bankinstrument->fetchAll();
    if ($result_bankinstrument[0]['total'] >= 1) {

        errorreturn("Unable to delete Ledgers because of the presence in bank instrument.");
    }

    // $sql_stocktransaction = "SELECT count(*) as total FROM inventory_stocktransaction WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? ";
    // $stmt_stocktransaction = $specific_db_conn->prepare($sql_stocktransaction);
    // $stmt_stocktransaction->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerid));
    // $result_stocktransaction = $stmt_stocktransaction->fetchAll();
    // if ($result_stocktransaction[0]['total'] >= 1) {

    //     errorreturn("Unable to delete Ledgers because of the presence in stock transaction.");
    // }

    $sql_classification = "SELECT count(*) as total FROM inventory_stock_classification WHERE workspace_id = ? and company_id =? and branch_id =? and book_id =? and ledgerid = ? ";
    $stmt_classification = $specific_db_conn->prepare($sql_classification);
    $stmt_classification->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerid));
    $result_classification = $stmt_classification->fetchAll();
    if ($result_classification[0]['total'] >= 1) {

        errorreturn("Unable to delete Ledgers because of the presence in stock classification.");
    }



    // = 6 or LIKE "%,".6.",%" or LIKE 6.",%"; or LIKE "%,".6;

    //added stock details
   $sql_stocks = "
    SELECT count(*) as total 
    FROM inventory_stockdetails 
    WHERE workspace_id = ? 
      AND company_id = ? 
      AND branch_id = ? 
      AND book_id = ? 
      AND (
          intra_tax_ledgerids LIKE ? 
          OR intra_tax_ledgerids LIKE ? 
          OR intra_tax_ledgerids LIKE ?
          OR inter_tax_ledgerids LIKE ? 
          OR inter_tax_ledgerids LIKE ? 
          OR inter_tax_ledgerids LIKE ?
          OR other_tax_ledgerids LIKE ? 
          OR other_tax_ledgerids LIKE ? 
          OR other_tax_ledgerids LIKE ?
      )";
    $stmt_stocks = $specific_db_conn->prepare($sql_stocks);
    // Patterns for the LIKE operator to search for the ledger ID
    $like_patterns = [
        "$ledgerid,%",   // Beginning of the list
        "%,$ledgerid,%", // Middle of the list
        "%,$ledgerid"    // End of the list
    ];
    $stmt_stocks->execute(array($workspace_id, $company_id, $branch_id, $book_id, $like_patterns[0],$like_patterns[1],$like_patterns[2],$like_patterns[0],$like_patterns[1],$like_patterns[2],$like_patterns[0],$like_patterns[1],$like_patterns[2]));
    $result_stocks = $stmt_stocks->fetchAll();
    if ($result_stocks[0]['total'] >= 1) {

        errorreturn("Unable to delete Ledgers because of the presence in stocks.");
    }
    
    $sql_inventory = "
    SELECT count(*) as total 
    FROM inventory_groups_info 
    WHERE workspace_id = ? 
      AND company_id = ? 
      AND branch_id = ? 
      AND book_id = ? 
      AND (
          intra_tax_ledgerids LIKE ? 
          OR intra_tax_ledgerids LIKE ? 
          OR intra_tax_ledgerids LIKE ?
          OR inter_tax_ledgerids LIKE ? 
          OR inter_tax_ledgerids LIKE ? 
          OR inter_tax_ledgerids LIKE ?
          OR other_tax_ledgerids LIKE ? 
          OR other_tax_ledgerids LIKE ? 
          OR other_tax_ledgerids LIKE ?
      )";
    $stmt_stocks = $specific_db_conn->prepare($sql_inventory);
    // Patterns for the LIKE operator to search for the ledger ID
    $like_patterns = [
        "$ledgerid,%",   // Beginning of the list
        "%,$ledgerid,%", // Middle of the list
        "%,$ledgerid"    // End of the list
    ];
    $stmt_inventory->execute(array($workspace_id, $company_id, $branch_id, $book_id, $like_patterns[0],$like_patterns[1],$like_patterns[2],$like_patterns[0],$like_patterns[1],$like_patterns[2],$like_patterns[0],$like_patterns[1],$like_patterns[2]));
    $result_inventory = $stmt_inventory->fetchAll();
    if ($result_inventory[0]['total'] >= 1) {

        errorreturn("Unable to delete Ledgers because of the presence in stocks.");
    }
    
    if (isset($addresses_id)) {
        $sql = "DELETE FROM act_ledger_addresses WHERE id = ? and workspace_id = ? and company_id = ? and branch_id = ? and book_id = ?";
        $stmt = $specific_db_conn->prepare($sql);
        $stmt->execute(array($addresses_id, $workspace_id, $company_id, $branch_id, $book_id));
        $count_addresss = $stmt->rowCount();
        //   if ($count_addresss == 1) {
        //     return "Delete ledger address Successfully";
        // } else {
        //     errorreturn("unable to delete ledger addresses");
        // }
    }
    
    $sql = "DELETE FROM act_ledgerdetails WHERE id = ? and workspace_id = ? and company_id =? and branch_id = ? and book_id = ?";
    $stmt = $specific_db_conn->prepare($sql);
    $stmt->execute(array($ledgerid, $workspace_id, $company_id, $branch_id, $book_id));
    $count = $stmt->rowCount();

    $specific_db_conn->commit();

    if ($count == 1) {
        return "Delete ledger Successfully";
    } else {
        errorreturn("unable to delete ledger");
    }
    
    } catch (Exception $e) {
        $specific_db_conn->rollBack();
        errorreturn('Error : ' . $e->getMessage());
    }
    
}

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

    $company_id = trim($postdata['company_id']);
    $branch_id = trim($postdata['branch_id']);
    $book_id = trim($postdata['book_id']);
    $ledgerid = trim($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);
        }
    }

    $success['data'] = deleteLedgerDetails($specific_db_conn, $ledgerid, $workspace_id, $company_id, $branch_id, $book_id);
    successreturn($success);
}
