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

$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);
}

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.");
    }

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

    if (!is_array($branch_id) || count($branch_id) <= 0) {
        errorreturn("Select at least one branch.");
    }

    if (!in_array("all", $branch_id)) {
        $imploded_branch_ids = "('" . implode("','", $branch_id) . "')";
        $count_ids = count($branch_id);

        $sql_codes = $conn_rjllearning_specific->prepare("SELECT count(*) as total FROM branch WHERE id IN $imploded_branch_ids AND status =?");
        $sql_codes->execute(array('1'));
        $result_branch = $sql_codes->fetchAll()[0]['total'];

        if ($result_branch != $count_ids) {
            errorreturn("Branch Not Found.");
        }

        $imploded_branchids = "'" . implode("','", $branch_id) . "'";
    } else {
        // If 'all' is in the array or the value is '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 {

        if (in_array('all', $branch_id)) {
            // Fetch all distinct branch_ids if 'all' is present
            $sql_get_branch = "SELECT id FROM branch WHERE institution_id = ?";
            $stmt_get_branch = $conn_rjllearning_specific->prepare($sql_get_branch);
            $stmt_get_branch->execute([$institution_id]);
            $result_get_branch = $stmt_get_branch->fetchAll();
            foreach ($result_get_branch as $row) {
                $finware_branch_ids[] = $row['id'];
            }
        } else {
            // If branch_id is not 'all', just use the provided branch_id
            $finware_branch_ids = $branch_id;  // Ensure $branch_ids is always an array
        }

        // Fetch the class names for the given institution and branch
        if (is_array($finware_branch_ids)) {
            foreach ($finware_branch_ids as $branch_class) {
                $sql_get_classnames = "SELECT classname FROM class_info WHERE institution_id = ? AND (branch_id LIKE ? or branch_id LIKE ?)";
                $stmt_get_classnames = $conn_rjllearning_specific->prepare($sql_get_classnames);
                $stmt_get_classnames->execute([$institution_id, "%'" . $branch_class . "'%", 'all']);
                $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 ($finware_branch_ids as $learning_branch_id) {
            // Fetch the branch details
            $branch = getBranchDetails($conn_rjllearning_specific, $learning_branch_id, $institution_id);
            // print_R($branch);die();
            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.");
    }

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

    // 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'];
    }
    $conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    $conn_rjllearning_specific->beginTransaction();
    try {
        $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[0] != 'all') {
            errorreturn("Cannot change a section with 'all' branch to specific branches.");
        }


        if (is_array($branch_id) && $branch_id[0] != 'all') {
            // Ensure $branch_id is an array and has elements
            if (count($branch_id) <= 0) {
                errorreturn("Select at least one branch.");
            }

            // Convert branch IDs into a safe, comma-separated string for SQL
            $imploded_branch_ids = "('" . implode("','", $branch_id) . "')";
            $count_ids = count($branch_id);

            // Check if the selected branches exist and are active
            $sql_codes = $conn_rjllearning_specific->prepare("SELECT count(*) as total FROM branch WHERE id IN $imploded_branch_ids AND status = ?");
            $sql_codes->execute(['1']);
            $result_branch = $sql_codes->fetch(PDO::FETCH_ASSOC)['total']; // Fetch count from query

            if ($result_branch != $count_ids) {
                errorreturn("Branch Not Found.");
            }

            // Prepare $imploded_branchids for further use
            $imploded_branchids = "'" . implode("','", $branch_id) . "'";
        } else {
            // Handle the case where 'branch_id' is 'all'
            $imploded_branchids = 'all'; // 'all' will remain as a string
        }

        // 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[0] != '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\"%' )";
                    $query_announcement = "SELECT id FROM announcement WHERE institution_id = $institution_id AND (branch_id = '$removed_branch' OR branch_id = 'all') AND (section_id = '$id' )";
                    $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\"%' )";
                    $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\"%' )";

                    // 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'];

        if (in_array('all', $branch_id)) {
            // Fetch all distinct branch_ids if 'all' is present
            $sql_get_branch = "SELECT id FROM branch WHERE institution_id = ?";
            $stmt_get_branch = $conn_rjllearning_specific->prepare($sql_get_branch);
            $stmt_get_branch->execute([$institution_id]);
            $result_get_branch = $stmt_get_branch->fetchAll();
            foreach ($result_get_branch as $row) {
                $finware_branch_ids[] = $row['id'];
            }
        } else {
            // If branch_id is not 'all', just use the provided branch_id
            $finware_branch_ids = $branch_id;  // Ensure $branch_ids is always an array
        }

        foreach ($finware_branch_ids 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));

        $conn_rjllearning_specific->commit();
        successreturn("Updated section Successfully");
    } catch (Exception $e) {
        $conn_rjllearning_specific->rollBack();
        errorreturn("Error : " . $e->getMessage());
    }
} 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");
}
