<?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';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

//aws image store
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";

require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = json_decode(file_get_contents("php://input"), true);
// print_r($postdata);
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);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;
$class_id = $jwt_validate->data->class;
$section_id = $jwt_validate->data->section;

$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["student"], null, null, $userid);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
validateStudentClassSection($conn_rjllearning_specific, $userid, $institution_id, $branch_id, $class_id, $section_id);

$check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($check_academic_confirmation != true) {
    errorreturn("Access denied. Academic session not active.");
}
function get_Activity_planner($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $from_date, $to_date, $limit, $offset)
{
    $sql_count = "SELECT  count(*) as total_rows FROM activity_planner where institution_id =?";
    $array_params = [$institution_id];

    if ($branch_id == 'all') {
        $sql_count .= "";
    } else if ($branch_id !=  null  && $branch_id != 'all') {
        $sql_count .= " AND branch_id = ? ";
        $array_params[] = $branch_id;
    }

    if ($class_id == 'all') {
        $sql_count .= "";
    } else if ($class_id !=  null  && $class_id != 'all') {
        $sql_count .= " AND class_id = ? ";
        $array_params[] = $class_id;
    }

    if ($section_id == 'all') {
        $sql_count .= "";
    } else if ($section_id !=  null  and $section_id != 'all') {
        $sql_count .= " AND section_id = ? ";
        $array_params[] = $section_id;
    }

    if ($subject_id == 'all') {
        $sql_count .= "";
    } else if ($subject_id !=  null  && $subject_id != 'all') {
        $sql_count .= " AND subject_id = ? ";
        $array_params[] = $subject_id;
    }

    if ($search_string != null) {
        $sql_count .= " AND description LIKE ? ";
        $array_params[] = '%' . $search_string . '%'; // Append to $array_params
    }

    if ($from_date != null && $to_date != null) {
        $sql_count .= " AND date_created BETWEEN ? AND ?";
        $array_params[] = $from_date;
        $array_params[] = $to_date;
    }
    
    // print_r($array_params);

    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    if ($limit == 'all') {

        $sql_session = "SELECT * FROM activity_planner where institution_id = ?";
        $array_params = [$institution_id];

        if ($branch_id == 'all') {
            $sql_session .= "";
        } else if ($branch_id !=  null && $branch_id != 'all') {
            $sql_session .= " AND (branch_id = ? OR branch_id = 'all')";
            $array_params[] = $branch_id ;
        }

        if ($class_id == 'all') {
            $sql_session .= "";
        } else if ($class_id !=  null  && $class_id != 'all') {
            $sql_session .= " AND (class_id = ? OR class_id = 'all')";
            $array_params[] = $class_id ;
        }

        if ($section_id == 'all') {
            $sql_session .= "";
        } else if ($section_id !=  null  and $section_id != 'all') {
            $sql_session .= " AND (section_id = ? OR section_id = 'all')";
            $array_params[] = $section_id ;
        }

        if ($subject_id == 'all') {
            $sql_session .= "";
        } else if ($subject_id !=  null  && $subject_id != 'all') {
            $sql_session .= " AND subject_id = ? ";
            $array_params[] = $subject_id;
        }

        if ($search_string != null) {
            $sql_session .= " AND description LIKE ? ";
            $array_params[] = '%' . $search_string . '%'; // Append to $array_params
        }

        // Add date range condition
        if ($from_date != null && $to_date != null) {
            $sql_session .= " AND date_created BETWEEN ? AND ?";
            $array_params[] = $from_date;
            $array_params[] = $to_date;
        }

        $sql_session .=  " order by date_created desc ";
        // print_r($sql_session);
    } else {
        $sql_session = "SELECT * FROM activity_planner WHERE institution_id = ?";
        $array_params = [$institution_id];

         if ($branch_id == 'all') {
            $sql_session .= "";
        } else if ($branch_id !=  null && $branch_id != 'all') {
            $sql_session .= " AND (branch_id = ? OR branch_id = 'all')";
            $array_params[] = $branch_id ;
        }

        if ($class_id == 'all') {
            $sql_session .= "";
        } else if ($class_id !=  null  && $class_id != 'all') {
            $sql_session .= " AND (class_id = ? OR class_id = 'all')";
            $array_params[] = $class_id ;
        }

        if ($section_id == 'all') {
            $sql_session .= "";
        } else if ($section_id !=  null  and $section_id != 'all') {
            $sql_session .= " AND (section_id = ? OR section_id = 'all')";
            $array_params[] = $section_id ;
        }

        if ($subject_id == 'all') {
            $sql_session .= "";
        } else if ($subject_id !=  null  && $subject_id != 'all') {
            $sql_session .= " AND subject_id = ? ";
            $array_params[] = $subject_id;
        }

        if ($search_string != null) {
            $sql_session .= " AND description LIKE ? ";
            $array_params[] = '%' . $search_string . '%'; // Append to $array_params
        }

        // Add date range condition
        if ($from_date != null && $to_date != null) {
            $sql_session .= " AND date_created BETWEEN ? AND ?";
            $array_params[] = $from_date;
            $array_params[] = $to_date;
        }
        $sql_session .= " order by date_created desc ";
        $sql_session .= " LIMIT " . $offset . " , " . $limit . "";
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_session);
  
    $stmt->execute($array_params);
    $session_rows = $stmt->fetchAll();
    
    if(!$session_rows){
        errorreturn("no data available");
    }

    $array_return = [];

    foreach ($session_rows as $rows) {
        if ($rows['branch_id'] == 'all' ) {
            $branch_info = array('branch_id' => 'all', 'branch_name' => 'All branches');
        } else {
            $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);
        }
        
        // Class Info
        if ($rows['class_id'] == 'all' ) {
            $class_info = array('class_id' => 'all', 'class_name' => 'All Classes');
        } else {
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows['class_id']); 
        }
        
        // Section Info
        if ($rows['section_id'] == 'all') {
            $section_info = array('section_id' => 'all', 'section_name' => 'All Sections');
        } else {
            $section_info = getSection($conn_rjllearning_specific, $institution_id, $rows['section_id']);
        }
        
        if ($rows['faculty_id'] == 'all' ) {
            $faculty_info = array('faculty_id' => 'all', 'faculty_name' => 'All Faculty');
        } else {
            $faculty_info = getFacultyInfo($conn_rjllearning_specific, $institution_id, $rows['faculty_id']);
        }
        // $subject_info = $rows['subject_id'] == 'all' ? array('subject_id' => 'all', 'name' => ucwords('all')) : 
        // getSubject($conn_rjllearning_specific, $institution_id, $rows['subject_id']);

        $schedule_details = json_decode($rows['schedule_details'], true);

        $array_return[] = array(
            'activty_planner_id' => $rows['id'],
            'institution_id' => $rows['institution_id'],
            'branch' => $branch_info,
            'faculty' => $faculty_info,
            'from_date' => $rows['from_date'],
            'to_date' => $rows['to_date'],
            'class_info' => $class_info, 
            'section_info' => $section_info, 
            // 'subject_info' => $subject_info, 
            'schedule_details' => $schedule_details, 
            'description' => $rows['description'], 
            'date_created' => $rows['date_created'],
            'created_by' => $rows['created_by'],
            'last_modified_by' => $rows['last_modified_by'],
            'last_modified_at' => $rows['last_modified_at'],
            'status' => $rows['status'],
        );
    }

    if (count($session_rows) < 50) {

        return array('total_rows' => $totalrows, 'planner_activity_info' => $array_return, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'planner_activity_info' => $array_return, 'maxreach' => 0);
    }
}

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

    $subject_id = isset($postdata['subject_id']) && checkIfIssetAndNotEmpty($postdata['subject_id']) ? ($postdata['subject_id']) : 'all';
    
    $from_date = isset($postdata['from_date']) && !empty($postdata['from_date']) ? trim($postdata['from_date']) : date('Y-m-d');
    $to_date = isset($postdata['to_date']) && !empty($postdata['to_date']) ? trim($postdata['to_date']) : $from_date;
    
    if ($from_date > $to_date) {
        errorreturn('Invalid Date format');
    }

    if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = get_Activity_planner($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, 
        $section_id, $from_date, $to_date, $limit, $offset);
        successreturn($success);
    } else {
        $success['data'] = get_Activity_planner($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, 
        $section_id, $from_date, $to_date, $limit, null);
        successreturn($success);
    }
}
