<?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/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
// Curl api for alter class
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_class_groups.php';

require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_add_finware_class_groups.php';

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

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['classname']) or !checkIfIssetAndNotEmpty($postdata['classname']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['class_order']) or !checkIfIssetAndNotEmpty($postdata['class_order']) 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);
}

$institution_id = trim($postdata['institution_id']);
$classname = ucwords(trim($postdata['classname']));
$branch_id = $postdata['branch_id'];
$class_order = $postdata['class_order'];

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

// if (!checkOnlyCharcterNumericwithSpace($classname)) { // for english chars + numbers only

//     errorreturn('Invalid class name');
// }

if ($branch_id != 'all' && !in_array('all', $branch_id)) {

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

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


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

    if (in_array('all', $branch_id)) {
        // Check if a class with 'all' as branch_id already exists
        $sql_check_all = "SELECT 1 FROM class_info WHERE institution_id = ? AND branch_id = 'all' AND classname = ?";
        $stmt_check_all = $conn_rjllearning_specific->prepare($sql_check_all);
        $stmt_check_all->execute([$institution_id, $classname]);
        $result_check_all = $stmt_check_all->fetch();

        if ($result_check_all) {
            errorreturn("Class already exists for all branches.");
        }
    }


    if (($branch_id != 'all' && !in_array('all', $branch_id))) {
        // Ensure $branch_id is an array
        if (!is_array($branch_id)) {
            $branch_id = [$branch_id];
        }

        // Prepare placeholders for the IN clause
        $placeholders = implode(',', array_fill(0, count($branch_id), '?'));

        // Prepare the SQL query
        $sql = "SELECT *  FROM class_info WHERE institution_id = ? AND (branch_id IN ($placeholders) OR branch_id = 'all')  AND classname = ?";
        $res = $conn_rjllearning_specific->prepare($sql);
        $params = array_merge([$institution_id], $branch_id, [$classname]);
        $res->execute($params);
        $result = $res->fetchAll();
        if (count($result) >= 1) {
            errorreturn("Class Name or class order already exists");
        }
    }
    $conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    $conn_rjllearning_specific->beginTransaction();
    try {

        // Fetch all distinct branch_ids if 'all' is present
        if (in_array('all', $branch_id)) {
            // Fetch all distinct branch_ids when '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();
            $branch_id_array = [];
            $branch_id = [];
            foreach ($result_get_branch as $row) {
                $branch_id[] = $row['id'];
            }
        }


        // Fetch all distinct branch_ids when 'all' is present
        // $sql_get_branch = "SELECT DISTINCT section_name FROM section_info WHERE institution_id = ? and (branch_id = 'all' or branch_id LIKE ?)";
        // $stmt_get_branch = $conn_rjllearning_specific->prepare($sql_get_branch);
        // $stmt_get_branch->execute([$institution_id,"%'" . $branch_id . "'%"]);
        // $result_get_branch = $stmt_get_branch->fetchAll();
        // $sections = [];
        // foreach ($result_get_branch as $row) {
        //     $sections[] = $row['section_name'];
        // }
        // Fetch the class names for the given institution and branch
        if (is_array($branch_id) or in_array('all', $branch_id)) {
            foreach ($branch_id as $branch_section) {
                $sql_get_classnames = "SELECT DISTINCT section_name FROM section_info WHERE institution_id = ? AND (branch_id = 'all' or branch_id LIKE ?)";
                $stmt_get_classnames = $conn_rjllearning_specific->prepare($sql_get_classnames);
                $stmt_get_classnames->execute([$institution_id, "%'" . $branch_section . "'%"]);
                $section_names = $stmt_get_classnames->fetchAll();
                $sections = [];
                foreach ($section_names as $section_row) {
                    $sections[] = $section_row['section_name'];
                }
            }
        }
        // print_r($branch_id);die();

        foreach ($branch_id as $learning_branch_id) {
            // Fetch branch details for each branch ID
            $branch = getBranchDetails($conn_rjllearning_specific, $learning_branch_id, $institution_id);
            if (!empty($branch)) {
                // Create an array with the class name and function type
                $formattedData = array(
                    'classname' => $classname,
                    "sections" => $sections,
                );
                // Prepare the data for calling the function to add the class
                $class_data = array(
                    "workspace_id" => $workspace_id,
                    "branch" => $branch,
                    "class_info" => $formattedData,
                    "created_by" => $username
                );
                // Call the function to add the class (replace with the actual function)
                curlAddClassFinware($class_data);
            }
        }

        $sql = "INSERT INTO class_info(institution_id,branch_id,classname,class_order,status)VALUES(?,?,?,?,?)";
        $stmt =  $conn_rjllearning_specific->prepare($sql);
        $stmt->execute(array($institution_id, $imploded_branchids, $classname, $class_order, '1'));

        $id = $conn_rjllearning_specific->lastInsertId();
        $conn_rjllearning_specific->commit();
        successreturn(array('class_id' => $id, 'successmsg' => "Successfully class added."));
    } catch (Exception $e) {
        $conn_rjllearning_specific->rollBack();
        errorreturn("Error : " . $e->getMessage());
    }
} else if ($postdata['function_type'] == "alter_class") {


    if (!isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_id'])) {
        errorreturn('Error in updating the class.');
    } else {
        $id = $postdata['class_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 class_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 class with 'all' branch to specific branches.");
        }


        if ($branch_id[0] != 'all') {
            $res = $conn_rjllearning_specific->prepare("SELECT branch_id FROM class_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 (class_id LIKE '%\"$id\"%' )";
                    $query_announcement = "SELECT id FROM announcement WHERE institution_id = $institution_id AND (branch_id = '$removed_branch' OR branch_id = 'all') AND (class_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 (class_id LIKE '%\"$id\"%' )";
                    $query_students = "SELECT id FROM students WHERE institution_id = $institution_id AND branch_id = $removed_branch AND class_id = $id";
                    $query_assignments = "SELECT id FROM assignments WHERE institution_id = $institution_id AND branch_id = $removed_branch AND class_id = $id";
                    $query_timetable = "SELECT id FROM timetable WHERE institution_id = $institution_id AND branch_id = $removed_branch AND class_id = $id";
                    $query_lessons = "SELECT id FROM lessons WHERE institution_id = $institution_id AND (branch_id = '$removed_branch' OR branch_id = 'all') AND (class_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).");
                    }
                }
            }
        }

        $res = $conn_rjllearning_specific->prepare("SELECT id,institution_id FROM class_info WHERE id != ? and institution_id=? and classname= ? and class_order = ?");
        $res->execute(array($id, $institution_id, $classname, $class_order));
        $result1 = $res->fetchAll();
        if (count($result1) >= 1) {
            errorreturn("The class already exists.");
        }

        $sql = $conn_rjllearning_specific->prepare("SELECT id,institution_id,classname FROM class_info WHERE id = ? and institution_id=? ");
        $sql->execute(array($id, $institution_id));
        $resultClass = $sql->fetchAll();
        if (count($resultClass) != 1) {
            errorreturn("Class not found");
        }
        $existing_class = $resultClass[0]['classname'];
        // Fetch all distinct branch_ids if 'all' is present
        if (in_array('all', $branch_id)) {
            // Fetch all distinct branch_ids when '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();
            $branch_id = [];
            foreach ($result_get_branch as $row) {
                $branch_id[] = $row['id'];
            }
        }

        foreach ($branch_id as $learnning_branch_id) {
            $branch = getBranchDetails($conn_rjllearning_specific, $learnning_branch_id, $institution_id);
            if (!empty($branch)) {
                // Create array with student and branch details for formattedData
                $formattedData = array(
                    'classname' => $classname,
                    'existing_class' => $existing_class,
                    "function_type" => "alter"
                );
                $class_data  = array("workspace_id" => $workspace_id, "branch" => $branch, "class_info" => $formattedData, "created_by" => $username);
                curlAlterClassFinware($class_data);
            }
        }

        $sql_users = "UPDATE class_info SET branch_id = ?,classname=?,class_order = ? WHERE id=? and institution_id=?";
        $conn_rjllearning_specific->prepare($sql_users)->execute(array($imploded_branchids, $classname, $class_order, $id, $institution_id));


        $conn_rjllearning_specific->commit();
        successreturn("Updated class Successfully");
    } catch (Exception $e) {
        $conn_rjllearning_specific->rollBack();
        errorreturn("Error : " . $e->getMessage());
    }
}
