<?php
ini_set('display_errors', 1);
// this file is used to create all other users except superadmin
require_once '../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';

require_once $base_path_to_learning_resources . 'external_requests/learning_solutions_finware/curl_create_book_finware.php';

require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_function_branch_students.php';
require_once $base_path_to_learning_resources .  'external_requests/finware_curl/groups_ledgers/curl_create_ledger_finware.php';

//curl check existing book
require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_check_existing_book.php';
//book settings
require_once $base_path_to_learning .'admin_api/global_settings/attendance_settings/attendance_setting_functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';

//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

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

if (
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
    !isset($postdata['learning_branch_id']) or !checkIfIssetAndNotEmpty($postdata['learning_branch_id'])  or
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id'])  or
    !isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede 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;
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin', 'admin'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
require_once $base_path_to_learning . 'functions/common_functions.php';

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

    $institution_id = trim($postdata['institution_id']);
    $learning_branch_id = $postdata['learning_branch_id'];
    $company_id  = $postdata['solutions_company_id'];
    $branch_id = $postdata['solutions_branch_id'];
    $book_id = (isset($postdata['book_id']) and !empty($postdata['book_id'])) ? trim($postdata['book_id']) : null;

    $book_name = $postdata['book_name'];
    $book_opening_date = (date('Y-m-d', strtotime($postdata['book_opening_date'])));
    $book_closing_date = (date('Y-m-d', strtotime($postdata['book_closing_date'])));
    $financial_year_startdate = ($postdata['financial_year_startdate']);

    $password = trim($postdata['password']);

    // Query to fetch the hashed password from the database
    $sql = "SELECT password,email FROM users WHERE workspace_id = ? AND username = ?";
    $stmt = $conn_rjllearning->prepare($sql);
    $stmt->execute([$workspace_id, $created_by]);
    $result = $stmt->fetchAll();
    if (count($result) != 1) {
        // User not found
        errorreturn("User not found.");
    }
    $hashed_password_from_db = ($result[0]['password']);

    if (!password_verify($password, $hashed_password_from_db)) {
        errorreturn("Incorrect password. Contact admin.");
    }

    // Check if the branch already has necessary IDs
    $existing_branch = getBranchDetails($conn_rjllearning_specific, $learning_branch_id, $institution_id);
    if ($existing_branch) {
        if (
            !empty($existing_branch['rejoice_solutions_company_id']) &&
            !empty($existing_branch['rejoice_solutions_branch_id']) &&
            !empty($existing_branch['rejoice_finware_book_id'])
        ) {
            errorreturn("Branch already exists with required IDs. Editing is not allowed.");
        }
    }
    // Use a transaction to ensure data integrity
    $conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    $conn_rjllearning_specific->beginTransaction();
    try {
        $today_date = date('Y-m-d');
        $academic_session_name = compareDatesAcademicSession($conn_rjllearning_specific, $institution_id, $today_date, $maxdate = null, $must_be_active_academic = false);
        
         $book_setting_finware = getSpecificGlobalSettings($conn_rjllearning_specific,$institution_id,$learning_branch_id);
        // print_r($book_setting_finware);die();
         if (!empty($book_setting_finware)) {
             $global_setting = $book_setting_finware[0];
             // Get accounting settings 
             if (!empty($global_setting['accounting_setting'])) {
                 $accounting_setting = json_encode($global_setting['accounting_setting']);
             }
             $fee_concession_application = $global_setting['fee_concession_application'] ?? 0;
             $send_sms_on_fee_receipt = $global_setting['send_sms_on_fee_receipt'] ?? 0;
         }else{
            $accounting_setting = [
                'student_ledger_display' => 0,
                'student_receipt_mail_alert' => 0,
                'custom_sms_header' => ''
            ];
             $fee_concession_application = 0;
             $send_sms_on_fee_receipt = 0;
             $accounting_setting = json_encode($accounting_setting); 
         }

        // Only check if the book already exists when $book_id is available
        if ($book_id) {

            $book_data = array(
                'workspace_id' => $workspace_id,
                "company_id" => $company_id,
                "branch_id" => $branch_id,
                "book_id" => $book_id,
                "learning_branch_id" => $learning_branch_id,
                "academic_session_name" => $academic_session_name['name'],
                "active_academic_session" => $academic_session_name['active_session'],
                "accounting_setting"=>$accounting_setting,
                "fee_concession_application"=>$fee_concession_application,
                "send_sms_on_fee_receipt" =>$send_sms_on_fee_receipt
            );

            $book_data = curlCheckExistingBook($book_data); // Call the API to create the book
            //errorreturn('This book is already linked to another branch and cannot be connected again.');
        }
        // If book_id is not available, proceed to create a new book
        if (!$book_id) {
            // print_R($academic_session_name);die();
            // If book_id is null or empty, proceed to create a new book via the curl API
            
            //get company_id and branch_id of Rejoice Learning and then get a create curl book in finware
            $book_info = array(
                'workspace_id' => $workspace_id,
                "company_id" => $company_id,
                "branch_id" => $branch_id,
                "book_name" => $book_name,
                "book_opening_date" => $book_opening_date,
                "book_closing_date" => $book_closing_date,
                "financial_year_startdate" => $financial_year_startdate,
                "function_type_book" => "add_book",
                "learning_branch_id" => $learning_branch_id,
                "academic_session_name" => $academic_session_name['name'],
                "created_by" => $created_by,
                "active_academic_session" => $academic_session_name['active_session'],
                "accounting_setting"=>$accounting_setting,
                "fee_concession_application"=>$fee_concession_application,
                "send_sms_on_fee_receipt" =>$send_sms_on_fee_receipt
                
            );

            $book_data = curlBookCreate($book_info); // Call the API to create the book
            $book_id = $book_data['book_id'];
        }


        $sql = "UPDATE branch SET rejoice_solutions_company_id=?, rejoice_solutions_branch_id=?,rejoice_finware_book_id=? where id = ? AND institution_id= ?";
        $conn_rjllearning_specific->prepare($sql)->execute(array($company_id, $branch_id, $book_id, $learning_branch_id, $institution_id));

        $branch = getBranchDetails($conn_rjllearning_specific, $learning_branch_id, $institution_id);

        $students = getStudentsByBranch($conn_rjllearning_specific, $learning_branch_id, $institution_id);
        // Get distinct classes and sections 
        $groups = getDistinctClassesAndSections($conn_rjllearning_specific, $learning_branch_id, $institution_id);
        // print_r($groups);die();
        if (!empty($students) or !empty($groups)) {
            // Create final array containing branch info, groups, and student data
            $finalArray = array('workspace_id' => $workspace_id, 'branch' =>  $branch, 'students' => $students, 'groups' => $groups, 'function_type' => 'add', "created_by" => $created_by);

            // Send the final array to your curl function or process it as needed
            $response = CurlLedgerCreateStudents($finalArray);
        }
        $conn_rjllearning_specific->commit();
        successreturn("Students and Groups added successfully in Finware.");
    } catch (Exception $e) {
        $conn_rjllearning_specific->rollBack();
        errorreturn("Failed to update branch details. " . $e->getMessage());
    }
}
