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

function fetchExistingMeetings($conn_rjllearning_specific, $institution_id, $branch_id, $subject_id, $search_string, $section_id, $class_id, $student_id, $from_date, $to_date, $limit, $offset)
{
    try {
        // Initialize query
        $query = "SELECT * 
                  FROM class_meetings 
                  WHERE institution_id = ? AND status = 1";
        $params = [$institution_id];

        // Dynamically build query based on filters
        if ($branch_id != 'all' && $branch_id != null) {
            $query .= " AND branch_id = ?";
            $params[] = $branch_id;
        }
        
        if ($class_id != 'all' && $class_id != null) {
            $query .= " AND class_id = ?";
            $params[] = $class_id;
        }

        if ($search_string != null) {
            $query .= " AND meeting_link LIKE ?";
            $params[] = '%' . $search_string . '%';
        }

        if ($from_date != null && $to_date != null) {
            $query .= " AND date_created BETWEEN ? AND ?";
            $params[] = $from_date;
            $params[] = $to_date;
        }


        $query .= " order by date_created desc, time_created desc ";
        if ($limit != 'all') {
            $query .= "LIMIT " . $offset . " ," . $limit . "";
        }
        // Prepare and execute query
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute($params);

        // Get row count before fetching results
        $rowCount = $stmt->rowCount();

        // Fetch the result
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $array_return = [];  // Initialize an array to store final result with extra info

        foreach ($result as $rows) {
            $section_id = $rows['section_id'];
            $section_info = [];

            // Handle section information
            if ($section_id === 'all') {
                $section_info[] = ['section_id' => 'all', 'section_name' => 'All'];
            } else {
                // Always decode JSON strings
                if (is_string($section_id)) {
                    $decoded = json_decode($section_id, true);
                    $section_id = $decoded !== null ? $decoded : [$section_id];
                }

                // Ensure it’s a flat array of integers/strings
                $section_id = array_map('intval', (array)$section_id);

                if (!empty($section_id)) {
                    $placeholders = implode(',', array_fill(0, count($section_id), '?'));
                    $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($placeholders)";
                    $stmt = $conn_rjllearning_specific->prepare($sql);
                    $stmt->execute(array_merge([$institution_id], $section_id));
                    $section_rows = $stmt->fetchAll();
                    foreach ($section_rows as $section_data) {
                        $section_info[] = [
                            'section_id' => $section_data['id'],
                            'section_name' => $section_data['section_name']
                        ];
                    }
                }
            }


            $student_id = $rows['student_id'];
            // Check if student_id is a string and decode if it's a JSON string
            if (is_string($student_id)) {
                $student_id = json_decode($student_id, true);
            }

            // Check if the student_id is 'all'
            if ($student_id === null) {
                // If null, return info for all students
                $student_info = [['student_id' => 'all', 'student_name' => 'All Students']];
            } else {
                // Ensure student_id is an array
                if (!is_array($student_id)) {
                    $student_id = [$student_id];
                }

                // Prepare placeholders for the SQL query
                $placeholders = implode(',', array_fill(0, count($student_id), '?'));
                $sql = "SELECT * FROM students WHERE institution_id = ? AND user_id IN ($placeholders)";

                // Prepare and execute the SQL statement
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute(array_merge([$institution_id], $student_id));

                // Fetch the student rows
                $student_rows = $stmt->fetchAll();

                // Prepare student info array
                $student_info = [];
                foreach ($student_rows as $student_data) {
                    $student_info[] = array('student_id' => $student_data['user_id'], 'student_name' => $student_data['name']);
                }
            }


            // Get the current time in H:i:s format (time only)
            // $current_time = date('H:i:s'); 

            // // Get the meeting's end time
            // $end_time = $rows['end_time']; 

            // // Compare the end time with the current time
            // $meeting_date = $rows['date']; // Backend stores the date in 'YYYY-MM-DD' format
            // $meeting_datetime_str = $meeting_date . ' ' . $end_time; // Combine date and time

            // $meeting_datetime = new DateTime($meeting_datetime_str); // Create a DateTime object

            // // Compare the current date and time with the meeting's end time
            // if ($meeting_datetime < new DateTime()) {
            //     // If the meeting's end time (with date) has passed, set the meeting link and code to null
            //     $meeting_link = null;
            //     $meet_code = null;
            //     $meeting_password = null;
            // } else {
            //     // Otherwise, use the original meeting link and code
            //     $meeting_link = $rows['meeting_link'];
            //     $meet_code = $rows['meet_code'];
            //     $meeting_password = $rows['meeting_password'];
            // }

            $meeting_link = isset($rows['meeting_link']) && !empty($rows['meeting_link']) ? $rows['meeting_link'] : null;
            $meet_code = isset($rows['meet_code']) && !empty($rows['meet_code']) ? $rows['meet_code'] : null;
            $meeting_password = isset($rows['meeting_password']) && !empty($rows['meeting_password']) ? $rows['meeting_password'] : null;

            // Add class and subject information
            if ($rows['class_id'] == 'all') {
                $class_info = ['class_id' => $rows['class_id'], 'class_name' => ucwords($rows['class_id'])];
            } else {
                $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows['class_id']);
            }

            if ($rows['branch_id'] == 'all') {
                $branch_info = ['branch_id' => $rows['branch_id'], 'name' => ucwords($rows['branch_id'])];
            } else {
                $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);
            }

            if ($rows['subject_id'] == 'all' || $rows['subject_id'] == null) {
                $subject_info = ['subject_id' => 'all', 'subject_name' => ucwords('All Subjects')];
            } else {
                $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $rows['subject_id']);
            }

            // Add everything to the result
            $array_return[] = [
                'id' => $rows['id'],
                'institution_id' => $rows['institution_id'],
                'branch_id' => $branch_info,
                'class_id' => $class_info,
                'section_id' => $section_info,
                'subject_id' => $subject_info,
                'student_info' => $student_info,
                'meeting_link' => $meeting_link,
                'meeting_password' => $meeting_password,
                'meet_code' => $meet_code,
                'date' => $rows['date'],
                'start_time' => $rows['start_time'],
                'end_time' => $rows['end_time'],
                'added_by' => $rows['added_by'],
                'date_created' => $rows['date_created'],
                'time_created' => $rows['time_created'],
                'status' => $rows['status'],

            ];
        }

        // Return the data and row count
        if ($rowCount > 0) {
            return ['link_data' => $array_return, 'total_rows' => $rowCount, 'maxreach' => 1];
        } else {
            return ['link_data' => $array_return, 'total_rows' => $rowCount, 'maxreach' => 0];
        }
    } catch (Exception $e) {
        return ['status' => 'error', 'message' => $e->getMessage()];
    }
}


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


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

    // Validate inputs and set defaults

    $subject_id = isset($postdata['subject_id']) && !empty($postdata['subject_id']) ? trim($postdata['subject_id']) : null;
    $search_string = isset($postdata['search_string']) && !empty($postdata['search_string']) ? trim($postdata['search_string']) : null;
    $section_id = isset($postdata['section_id']) && !empty($postdata['section_id']) ? trim($postdata['section_id']) : "all";
    $student_id = isset($postdata['student_id']) && !empty($postdata['student_id']) ? trim($postdata['student_id']) : "all";
    $class_id = isset($postdata['class_id']) && !empty($postdata['class_id']) ? trim($postdata['class_id']) : null;
    $from_date = isset($postdata['from_date']) && !empty($postdata['from_date']) ? trim($postdata['from_date']) : null;
    $to_date = isset($postdata['to_date']) && !empty($postdata['to_date']) ? trim($postdata['to_date']) : null;

    if ($from_date && $to_date && $from_date > $to_date) {
        errorreturn(['message' => 'Invalid Date format']);
    }

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

    // Fetch meetings data
    $response = fetchExistingMeetings(
        $conn_rjllearning_specific,
        $institution_id,
        $branch_id,
        $subject_id,
        $search_string,
        $section_id,
        $class_id,
        $student_id,
        $from_date,
        $to_date,
        $limit,
        $offset
    );

    if ($response) {
        successreturn(['data' => $response]);
    } else {
        errorreturn('empty data');
    }
}
