<?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';
//validation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
//dynamic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
// require_once $base_path_to_learning . 'admin_api/modules/students/student_functions.php';
// require_once $base_path_to_learning_resources . 'lib/cron_jobs/function/function.php';
require_once $base_path_to_learning . 'admin_api/modules/class_meetings/class_meeting_notification.php';
require_once $base_path_to_learning_resources . 'lib/task_schedule/task_scheduler_functions.php';

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

$postdata = json_decode(file_get_contents("php://input"), true);
// $postdata = $_POST;
$requiredFields = [
    'institution_id',
    'api_signature',
    'function_type',
    'jwt_token'
];

foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn(["message" => "All * fields are required. Missing field: $field"]);
    }
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
// then workspace_id is in decoded 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);
}

require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

$institution_id = $postdata['institution_id'];

$branch_id = isset($postdata['branch_id']) ? $postdata['branch_id'] : 'all';
$class_id = isset($postdata['class_id']) ? $postdata['class_id'] : 'all';
$section_id = isset($postdata['section_id']) ? $postdata['section_id'] : 'all';
$subject_id = isset($postdata['subject_id']) ? $postdata['subject_id'] : null;
$student_id = isset($postdata['student_id']) ? $postdata['student_id'] : null;  // Can be null
$meeting_link = $postdata['meeting_link'];
$meet_code = isset($postdata['meet_code']) ? $postdata['meet_code'] : null;

$date = isset($postdata['date']) ? $postdata['date'] : date('Y-m-d');
$meeting_password = isset($postdata['meeting_password']) ? $postdata['meeting_password'] : null;
$start_time = isset($postdata['start_time']) ? $postdata['start_time'] : date('h-i-s');  // Can be null
$end_time = isset($postdata['end_time']) ? $postdata['end_time'] : null;
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}
if (!isset($postdata['start_time']) || !isset($postdata['end_time'])) {
    errorreturn("Start time and end time are required.");
}

$start_datetime = new DateTime("$date $start_time");
$end_datetime = new DateTime("$date $end_time");

if ($end_datetime <= $start_datetime) {
    $end_datetime->modify('+1 day');
}
// If end time is before start time, assume it's on the next day

if ($start_datetime >= $end_datetime) {
    errorreturn("Start time must be before end time.");
}
$current_time = date('H:i:s');
// if ($start_time < $current_time) {
//     errorreturn("Start time cannot be in the past.");
// }

// validateBranchClassSection($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $support_branch_all = 0, $checkClass = 0, $support_class_all = 0, $checkSection = 1,  $support_section_all = 1);

// Handle section_id (it can be specific or 'all')
if (isset($postdata['section_id']) && is_array($postdata['section_id'])) {
    $section_id = array_map('strval', array_filter($postdata['section_id'])); // Convert all values to string

    if (count($section_id) === 1 && $section_id[0] === 'all') {
        $json_section_id = 'all';
    } else {
        if (empty($section_id)) {
            errorreturn("Select at least one section.");
        }

        $json_section_id = json_encode($section_id, JSON_UNESCAPED_SLASHES); // Ensures ["1"] format
    }
} else {
    errorreturn("Select at least one section.");
}

// if (isset($postdata['student_id']) && is_array($postdata['student_id'])) {
//     $student_id = $postdata['student_id']; 

//     if (count($student_id) === 1 && $student_id[0] === 'all') {
//         // If 'all' is present, no need for further checks
//         $json_student_id = 'all';
//     } else {
//         // Handle the case when 'all' is not present
//         if (count($student_id) <= 0) {
//             errorreturn("Select at least one student.");
//         }
//         // Encode the valid student IDs
//         $json_student_id = json_encode($student_id);
//     }
// } else {
//     errorreturn("Select at least one student.");
// }

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

        $section_condition = "";
        $params = [$institution_id, $branch_id, $class_id, $date];
        
        if ($section_id !== 'all' && is_array($section_id)) {
            $section_conditions = [];
            foreach ($section_id as $sec) {
                $section_conditions[] = "(section_id LIKE ? OR section_id = 'all')";
                $params[] = '%"' . $sec . '"%';
            }
            if (!empty($section_conditions)) {
                $section_condition = " AND (" . implode(" OR ", $section_conditions) . ")";
            }
        }
        
        $fetch_query = "SELECT id, start_time, end_time FROM class_meetings 
                        WHERE institution_id = ? 
                        AND branch_id = ? 
                        AND class_id = ? 
                        AND date = ? 
                        
                        $section_condition";
        
        try {
            $fetch_stmt = $conn_rjllearning_specific->prepare($fetch_query);
            $fetch_stmt->execute($params);
            $existing_meetings = $fetch_stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            errorreturn("SQL Error: " . $e->getMessage());
        }
        
        foreach ($existing_meetings as $meeting) {
            $existing_start = strtotime($meeting['start_time']);
            $existing_end = strtotime($meeting['end_time']);
            $new_start = strtotime($start_time);
            $new_end = strtotime($end_time);
        
            // Handle overnight meetings
            if ($new_end <= $new_start) {
                $new_end = strtotime("+1 day", $new_end);
            }
            if ($existing_end <= $existing_start) {
                $existing_end = strtotime("+1 day", $existing_end);
            }
        
            // Overlapping checks
            if (
                ($new_start < $existing_end && $new_end > $existing_start) ||
                ($new_start >= $existing_start && $new_end <= $existing_end) ||
                ($new_start <= $existing_start && $new_end >= $existing_end)
            ) {
                errorreturn("Meeting already exists for the selected time slot.");
            }
        }

        // Prepare SQL Query for Insertion
        $query = "INSERT INTO class_meetings (institution_id, branch_id, class_id, section_id, subject_id, student_id, meeting_link, meeting_password, meet_code,date, start_time, end_time, added_by, date_created, time_created, status)
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?)";

        // Execute Query for Insertion
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute([$institution_id, $branch_id, $class_id, $json_section_id, $subject_id, $student_id, $meeting_link, $meeting_password, $meet_code, $date, $start_time, $end_time, $username, date('Y-m-d'), date('H:i:s'), 1]);

        // Get the last inserted ID
        $last_inserted_id = $conn_rjllearning_specific->lastInsertId();
        $current_time = time();  // Current timestamp

        if ($current_time >= (strtotime($start_time) - 600) && $current_time < strtotime($start_time)) {
            // If current time is within 10 minutes before start time

            // sendLiveClassNotification($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $json_section_id, $subject_id, $json_student_id, 'Join now', $meeting_link, $start_time, $workspace_id, $web_app_title);
        } else {
            // If more than 10 minutes away, schedule 10 minutes before the start time
            $schedule_time = strtotime($start_time) - 600;

            manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'live_meeting', $last_inserted_id, $date, $schedule_time, 1, $process_type = 'create');
        }
        // Respond with success message and last inserted ID
        successreturn(['message' => 'Meeting link stored successfully.', 'last_inserted_id' => $last_inserted_id]);
    } catch (Exception $e) {
        // Respond with error message if exception occurs
        errorreturn(['error' => $e->getMessage()]);
    }
} elseif ($postdata['function_type'] == "update_class_meeting_status") {
    try {
        $meeting_id = $postdata['meeting_id'];
        $status = isset($postdata['status']) ? $postdata['status'] : 1;
        $meeting_link = $postdata['meeting_link'];
        $meeting_password = isset($postdata['meeting_password']) ? $postdata['meeting_password'] : null;
        $class_id = $postdata['class_id'];
        $subject_id = $postdata['subject_id'];
        // Fetch the start_time of the meeting from the database
        $query = "SELECT start_time,date FROM class_meetings WHERE id = ?";
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute([$meeting_id]);
        $meeting = $stmt->fetch();

        if ($meeting) {
            // $existing_start_time = strtotime($meeting['start_time']);
            // $existing_date = strtotime($meeting['date']);
            // $current_time = time();
            // $current_date = strtotime(date('Y-m-d'));

            $existing_start_time = strtotime($meeting['date'] . ' ' . $meeting['start_time']);
            $current_time = time();
            
            // Debugging output
            
            // Check if start_time is in the past
            // if (!empty($meeting['start_time']) && $existing_start_time <= $current_time) {
            //     errorreturn("Cannot update: Meeting has already started!");
            // }

            // Update meeting details
            $query = "UPDATE class_meetings SET meeting_link = ?, meeting_password = ?, class_id = ?, section_id = ?, subject_id = ?, student_id = ?, status = ?,date=?,start_time=? ,end_time=?
                      WHERE id = ?";
            $stmt = $conn_rjllearning_specific->prepare($query);
            $stmt->execute([$meeting_link, $meeting_password, $class_id, $json_section_id, $subject_id, $student_id, $status, $date, $start_time, $end_time, $meeting_id]);
            $current_time = time();
            if ($current_time >= (strtotime($start_time) - 600) && $current_time < strtotime($start_time)) {
                // If current time is within 10 minutes before start time

                // sendLiveClassNotification($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $json_section_id, $subject_id, $json_student_id, 'Join now', $meeting_link, $start_time, $workspace_id, $web_app_title);
            } else {
                // If more than 10 minutes away, schedule 10 minutes before the start time
                $schedule_time = strtotime($start_time) - 600;

                manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'live_meeting', $meeting_id, $date, $schedule_time, 1, $process_type = 'alter');
            }

            successreturn(['message' => 'Meeting status updated successfully.']);
        } else {
            errorreturn(['error' => 'Meeting not found.']);
        }
    } catch (Exception $e) {
        errorreturn(['error' => $e->getMessage()]);
    }
}
