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

$required_fields = ['institution_id', 'api_signature', 'function_type', 'jwt_token'];

foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Field '$field' is 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;

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

function fetchExistingMeetings($conn_rjllearning_specific, $institution_id, $meeting_id)
{
    try {
        // Initialize query
        $query = "SELECT * 
                  FROM class_meetings 
                  WHERE institution_id = ? AND status = 1 AND id = ?";
        $params = [$institution_id, $meeting_id];

        // Prepare and execute query
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute($params);

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

        if (empty($result)) {
            errorreturn('No meeting found');
        }

        $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' => $section_id, 'section_name' => ucwords($section_id)];
            } else {
                if (is_string($section_id)) {
                    $section_id = json_decode($section_id, true);
                }
                if (!is_array($section_id)) {
                    $section_id = [$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']);
                }
            }

            // $current_time = date('H:i:s');
            // $end_time = $rows['end_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;

            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']);
            }

            $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 ['status' => 'success', 'data' => $array_return];
    } catch (Exception $e) {
        return ['status' => 'error', 'message' => $e->getMessage()];
    }
}

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

    $institution_id = trim($postdata['institution_id']);
    $meeting_id = trim($postdata['meeting_id']);

    $response = fetchExistingMeetings($conn_rjllearning_specific, $institution_id, $meeting_id);

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