<?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_faculty_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 faculty_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 LIKE ? OR section_id = 'all')";
        $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 remarks 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 faculty_planner where institution_id = ? and branch_id =?";
        $array_params = [$institution_id,$branch_id];

      

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

        if ($section_id == 'all') {
            $sql_session .= "";
        } else if ($section_id !=  null  and $section_id != 'all') {
            $sql_session .= " AND (section_id LIKE ? 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 remarks 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 faculty_planner where institution_id = ? and branch_id =?";
        $array_params = [$institution_id,$branch_id];

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

        if ($section_id == 'all') {
            $sql_session .= "";
        } else if ($section_id !=  null  and $section_id != 'all') {
            $sql_session .= " AND (section_id LIKE ? 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 remarks 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) {

        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);

        // =========================
        // Handle section_id (JSON)
        // =========================
             $section = [];
        $section_id = $rows['section_id'];
        $section_ids_array = json_decode($section_id, true);

        if ($section_id == 'all' || (is_array($section_ids_array) && in_array('all', $section_ids_array))) {
            $section[] = ['section_id' => 'all', 'section_name' => 'All Sections'];
        } elseif (!empty($section_ids_array) && is_array($section_ids_array)) {
            $imploded_section_ids = implode(',', array_map('intval', $section_ids_array));
            $sql_section = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($imploded_section_ids)";
            $stmt_section = $conn_rjllearning_specific->prepare($sql_section);
            $stmt_section->execute([$institution_id]);
            $section_rows = $stmt_section->fetchAll();

            foreach ($section_rows as $section_data) {
                $section[] = ['section_id' => $section_data['id'], 'section_name' => $section_data['section_name']];
            }
        }

        // --------------------
        // Resolve Class IDs
        // --------------------
          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']); 
        }

        $faculty_info = getFacultyInfo($conn_rjllearning_specific, $institution_id, $rows['faculty_id']);
        $subject_info = $rows['subject_id'] == 'all'
            ? ['subject_id' => 'all', 'subject_name' => 'All']
            : getSubject($conn_rjllearning_specific, $institution_id, $rows['subject_id']);


        $array_return[] = [
            'planner_id' => $rows['id'],
            'institution_id' => $rows['institution_id'],
            'branch' => $branch_info,
            'faculty' => $faculty_info,
            'academic_session' => $rows['academic_session'],
            'faculty_title' => $rows['faculty_title'],
            'faculty_description' => $rows['faculty_description'],
            'student_title' => $rows['student_title'],
            'student_description' => $rows['student_description'],
            'from_date' => $rows['from_date'],
            'to_date' => $rows['to_date'],
            'class_info' => $class_info,
            'section_info' => $section,
            'subject_info' => $subject_info,
            
            'remarks' => $rows['remarks'],
            '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, 'faculty_planner_info' => $array_return, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'faculty_planner_info' => $array_return, 'maxreach' => 0);
    }
}

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

    $subject_id = (!empty($postdata['subject_id']) && trim($postdata['subject_id'])) ? trim($postdata['subject_id']) : null;

    $search_string = (!empty($postdata['search_string']) && trim($postdata['search_string'])) ? trim($postdata['search_string']) : null;

    $from_date = (!empty($postdata['from_date']) && trim($postdata['from_date'])) ? trim($postdata['from_date']) : null;
    $to_date   = (!empty($postdata['to_date']) && trim($postdata['to_date'])) ? trim($postdata['to_date']) : null;

    if ($from_date && $to_date && $from_date > $to_date) {
        errorreturn('Invalid date range: "From Date" should not be after "To Date"');
    }

    $limit = isset($postdata['limit']) ? $postdata['limit'] : 50; // Default to 50 if not set

    $page = (isset($postdata['page']) && isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;
    $offset = ($limit !== 'all') ? (($page - 1) * $limit) : null;

    // Call the planner function
    $success['data'] = get_faculty_planner($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $section_id, $from_date, $to_date, $limit, $offset);

    successreturn($success);
}
