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

require_once '../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
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 . 'functions/common_functions.php';

// Curl api for alter section
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_update_finware_section_groups.php';

require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_add_finware_section_groups.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['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;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

$can_principal_edit_branch = canPrincipalEditBranch($branch_id);
if (!$can_principal_edit_branch) {
    errorretrun("Can not edit branch");
}
if ($postdata['function_type'] == "create_section") {

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

    
    $section_name = trim($postdata['section_name']);
    
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    // If branch_id is a string (not an array), convert it into an array
    if (!is_array($branch_id)) {
        $branch_id = [$branch_id];  // Make it an array
    }

    if ($branch_id != 'all') {
        // If 'all' is not in the array, proceed with the logic to handle the branches
        $imploded_branchids = "'" . implode("','", $branch_id) . "'";
    } else {
        // If 'all' is in the array, set imploded_branchids to 'all'
        $imploded_branchids = "all";
    }

    foreach ($branch_id as $branch_ids) {
        $sql_table = $conn_rjllearning_specific->prepare("SELECT COUNT(*) as total FROM section_info WHERE institution_id = ? AND branch_id LIKE ? AND LOWER(section_name) = ?");
        $sql_table->execute([$institution_id,'%' . $branch_ids . '%',strtolower($section_name)]);
        $result = $sql_table->fetch(PDO::FETCH_ASSOC);
        if ($result['total'] > 0) {
            errorreturn("This section name already exists for branch ID");
        }
    }

    // $imploded_branch_ids = "('" . implode("','", $branch_id) . "')"; // Implode branch_ids into a single string for the IN clause

    // $sql_table = $conn_rjllearning_specific->prepare(
    //     "SELECT COUNT(*) as total FROM section_info WHERE institution_id = ? AND branch_id IN $imploded_branch_ids AND section_name = ?"
    // );
    // $sql_table->execute([$institution_id, $section_name]);
    // $result = $sql_table->fetch(PDO::FETCH_ASSOC);
    // if ($result['total'] > 0) {
    //     errorreturn("This section name already exists for one of the provided branch IDs.");
    // }
    
    $conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    $conn_rjllearning_specific->beginTransaction();
    try {
        // Fetch the class names for the given institution and branch
        if (is_array($branch_id)) {
        foreach($branch_id as $branch_class){
            $sql_get_classnames = "SELECT classname FROM class_info WHERE institution_id = ? AND branch_id LIKE ?";
            $stmt_get_classnames = $conn_rjllearning_specific->prepare($sql_get_classnames);
            $stmt_get_classnames->execute([$institution_id,"%'" . $branch_class . "'%"]);
            $class_names = $stmt_get_classnames->fetchAll();
            $classes = [];
            foreach ($class_names as $class_row) {
                $classes[] = $class_row['classname'];
            }
          }
        }

        // Fetch class names for each branch and institution
        foreach ($branch_id as $learning_branch_id) {
            $branch = getBranchDetails($conn_rjllearning_specific, $learning_branch_id, $institution_id);
 
            if (!empty($branch)) {
                // Create array with section details and class names
                $formattedData = array(
                    'section_name' => $section_name, // The section name
                    'classes' => $classes // All class names for this branch
                );

                // Prepare data to be sent to the function
                $section_data = array(
                    "workspace_id" => $workspace_id,
                    "branch" => $branch,
                    "section_info" => $formattedData,
                    "created_by" => $username
                );

                // Call your function to alter the section
                curlAddSectionFinware($section_data);
            }
        }

        $sql = "INSERT INTO section_info(institution_id,branch_id,section_name,added_by,time_created,status)VALUES(?,?,?,?,?,?)";
        $stmt =  $conn_rjllearning_specific->prepare($sql);

        $stmt->execute(array($institution_id, $imploded_branchids, $section_name, $username, time(), '1'));
        $id = $conn_rjllearning_specific->lastInsertId();
        $conn_rjllearning_specific->commit();

        successreturn(array('id' => $id, 'successmsg' => "Successfully section added."));
    } catch (Exception $e) {
        $conn_rjllearning_specific->rollBack();
        errorreturn("Error : " . $e->getMessage());
    }

} else if ($postdata['function_type'] == "alter_section") {
    if (!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id'])  or !isset($postdata['section_name']) or !checkIfIssetAndNotEmpty($postdata['section_name'])) {
        errorreturn("All * fields are required.");
    }

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

    // Check if the academic session is active
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    // Check if section_id is provided
    if (!isset($postdata['section_id']) or !checkIfIssetAndNotEmpty($postdata['section_id'])) {
        errorreturn('Error in updating the academic session.');
    } else {
        $id = $postdata['section_id'];
    }

    $sql = $conn_rjllearning_specific->prepare("SELECT branch_id FROM section_info WHERE id = ?");
    $sql->execute([$id]);
    $existing_branch_id = $sql->fetch(PDO::FETCH_ASSOC)['branch_id'];

    // If the existing branch is 'all', we cannot change it to specific branches
    if ($existing_branch_id == 'all' &&  $branch_id != 'all') {
        errorreturn("Cannot change a section with 'all' branch to specific branches.");
    }


    // If branch_id is a string (not an array), convert it into an array
    if (!is_array($branch_id)) {
        $branch_id = [$branch_id];  // Make it an array
    }

    if ($branch_id != 'all') {
        // If 'all' is not in the array, proceed with the logic to handle the branches
        $imploded_branchids = "'" . implode("','", $branch_id) . "'";
    } else {
        // If 'all' is in the array, set imploded_branchids to 'all'
        $imploded_branchids = "all";
    }

    // Check for existing section with the same name
    $res = $conn_rjllearning_specific->prepare("SELECT id, institution_id FROM section_info WHERE id != ? and institution_id=? and section_name =?");
    $res->execute(array($id, $institution_id, $section_name));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("The Class Section already exists.");
    }

    // Handle branch removal validation

    if ($branch_id != 'all') {
        $res = $conn_rjllearning_specific->prepare("SELECT branch_id FROM section_info WHERE id = ?");
        $res->execute([$id]);
        $existing_branch_ids = explode(',', $res->fetch(PDO::FETCH_ASSOC)['branch_id']);
        // print_r($existing_branch_ids);
        if ($existing_branch_ids[0] != 'all') {
            $existing_branch_ids = array_map('intval', array_map(function ($branch) {
                return trim($branch, "'");
            }, $existing_branch_ids));

            $removed_branches = array_diff($existing_branch_ids, (array)$branch_id);

            foreach ($removed_branches as $removed_branch) {
                $branch_name = $removed_branch === 'all' ? 'all' : getBranchInfo($conn_rjllearning_specific, $institution_id, $removed_branch)['name'];

                // SQL queries for each module
                $query_homework = "SELECT id FROM homework WHERE institution_id = $institution_id AND branch_id = '$removed_branch' AND (section_id LIKE '%\"$id\"%' OR section_id = 'all')";
                $query_announcement = "SELECT id FROM announcement WHERE institution_id = $institution_id AND (branch_id = '$removed_branch' OR branch_id = 'all') AND (section_id = '$id' OR section_id = 'all')";
                $query_activity_mentor = "SELECT id FROM activity_mentor WHERE institution_id = $institution_id AND (branch_id LIKE '%\"$removed_branch\"%' OR branch_id = 'all') AND (section_id LIKE '%\"$id\"%' OR section_id = 'all')";
                $query_students = "SELECT id FROM students WHERE institution_id = $institution_id AND branch_id = $removed_branch AND section_id = $id";
                $query_assignments = "SELECT id FROM assignments WHERE institution_id = $institution_id AND branch_id = $removed_branch AND section_id = $id";
                $query_timetable = "SELECT id FROM timetable WHERE institution_id = $institution_id AND branch_id = $removed_branch AND section_id = $id";
                $query_lessons = "SELECT id FROM lessons WHERE institution_id = $institution_id AND (branch_id = '$removed_branch' OR branch_id = 'all') AND (section_id LIKE '%\"$id\"%' OR section_id = 'all')";

                // Execute the queries for each module and check if the branch is in use
                // Activity Mentor
                $stmt = $conn_rjllearning_specific->query($query_activity_mentor);
                if ($module_id = $stmt->fetchColumn()) {
                    errorreturn("Cannot remove branch $branch_name as it is still in use by activity_mentor (ID: $module_id).");
                }

                // Lessons
                $stmt = $conn_rjllearning_specific->query($query_lessons);
                if ($module_id = $stmt->fetchColumn()) {
                    errorreturn("Cannot remove branch $branch_name as it is still in use by lessons (ID: $module_id).");
                }
                // Announcement
                $stmt = $conn_rjllearning_specific->query($query_announcement);
                if ($module_id = $stmt->fetchColumn()) {
                    errorreturn("Cannot remove branch $branch_name as it is still in use by announcement (ID: $module_id).");
                }

                // Homework
                $stmt = $conn_rjllearning_specific->query($query_homework);
                if ($module_id = $stmt->fetchColumn()) {
                    errorreturn("Cannot remove branch $branch_name as it is still in use by homework (ID: $module_id).");
                }

                // Students
                $stmt = $conn_rjllearning_specific->query($query_students);
                if ($module_id = $stmt->fetchColumn()) {
                    errorreturn("Cannot remove branch $branch_name as it is still in use by students (ID: $module_id).");
                }

                // Assignments
                $stmt = $conn_rjllearning_specific->query($query_assignments);
                if ($module_id = $stmt->fetchColumn()) {
                    errorreturn("Cannot remove branch $branch_name as it is still in use by assignments (ID: $module_id).");
                }

                // Timetable
                $stmt = $conn_rjllearning_specific->query($query_timetable);
                if ($module_id = $stmt->fetchColumn()) {
                    errorreturn("Cannot remove branch $branch_name as it is still in use by timetable (ID: $module_id).");
                }
            }
        }
    }
    
    foreach ($branch_id as $branch_ids) {
        $sql_table = $conn_rjllearning_specific->prepare("SELECT COUNT(*) as total FROM section_info WHERE id != ? and institution_id = ? AND branch_id LIKE ? AND LOWER(section_name) = ?");
        $sql_table->execute([$id,$institution_id,'%' . $branch_ids . '%',strtolower($section_name)]);
        $result = $sql_table->fetch(PDO::FETCH_ASSOC);
        if ($result['total'] > 0) {
            errorreturn("This section name already exists for branch ID");
        }
    }

    $sql = $conn_rjllearning_specific->prepare("SELECT id,institution_id,section_name FROM section_info WHERE id = ? and institution_id=? ");
    $sql->execute(array($id, $institution_id));
    $resultSection = $sql->fetchAll();
    if (count($resultSection) != 1) {
        errorreturn("Section not found");
    }
    $existing_section = $resultSection[0]['section_name'];

    foreach ($branch_id as $learning_branch_id) {
        $branch = getBranchDetails($conn_rjllearning_specific, $learning_branch_id, $institution_id);
        if (!empty($branch)) {
            // Create array with student and branch details for formattedData
            $formattedData = array(
                'section_name' => $section_name,
                'existing_section' => $existing_section,
                "function_type" => "alter"
            );
            $section_data  = array("workspace_id" => $workspace_id, "branch" => $branch, "section_info" => $formattedData, "created_by" => $username);
            curlAlterSectionFinware($section_data);
        }
    }
        
    $sql_users = "UPDATE section_info SET branch_id = ?,section_name =? WHERE id=? and institution_id=?";
    $conn_rjllearning_specific->prepare($sql_users)->execute(array($imploded_branchids, $section_name, $id, $institution_id));

    successreturn("Updated section Successfully");
} else if ($postdata['function_type'] == "section_status") {

    if (!isset($postdata['section_id']) or !checkIfIssetAndNotEmpty($postdata['section_id']) or !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id'])) {
        errorreturn('Error in updating the academic session.');
    } else {
        $id = $postdata['section_id'];
        $institution_id = trim($postdata['institution_id']);
    }

    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }
    $res = $conn_rjllearning_specific->prepare("SELECT status FROM section_info WHERE id = ? and institution_id=?");
    $res->execute(array($id, $institution_id));
    $result1 = $res->fetchAll();

    if (count($result1) == 1) {
        $existing_status = $result1[0]['status'];

        if ($existing_status == '1') {
            $status = '0';
            $sql = "UPDATE section_info SET status=?  WHERE id = ? and institution_id=?";
            $conn_rjllearning_specific->prepare($sql)->execute(array($status, $id, $institution_id));
        } else if ($existing_status == '0') {
            $status = '1';
            $sql = "UPDATE section_info SET status=?  WHERE id = ? and institution_id=? ";
            $conn_rjllearning_specific->prepare($sql)->execute(array($status, $id, $institution_id));
        }
    }
    successreturn("Section Status Updated Successfully");
}
