<?php
ini_set('display_errors', 1);

require_once '/home/rejoicebilldesk/public_html/rjllearning_development/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';
require_once $base_path_to_learning . 'admin_api/modules/timetable/timetable_functions.php';

//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

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

foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.$field");
    }
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract common JWT data
$userid       = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username     = $jwt_validate->data->username;
$role         = $jwt_validate->data->role;

// Decide where to get institution_id and branch_id based on the user's role
if ($role === 'teacher' || $role === 'principal') {
    // For teachers and principals, use values from the JWT token
    $institution_id = $jwt_validate->data->institution_id;
    $branch_id      = $jwt_validate->data->branch_id;
} else {
    // For other roles, use the values provided by the frontend
    $institution_id = trim($postdata['institution_id']);
    $branch_id      = trim($postdata['branch_id']);
}


$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin','principal'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

if (empty($postdata['timetable_info'])) {
    errorreturn("Timetable required.");
}


$timetable_info = $postdata['timetable_info']; 

// Validate academic session
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$academic_id) {
    errorreturn("Access denied. Academic session not active.");
}



if($postdata['function_type'] == 'create_automatic_timetable'){
$conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
$conn_rjllearning_specific->beginTransaction();

$sql_check_time_lapping = "SELECT COUNT(*) as conflict_count FROM timetable 
                           WHERE type = 'timetable' 
                           AND faculty_id = ? 
                           AND academic_session_id = ? 
                           AND institution_id = ? 
                           AND branch_id = ? 
                           AND day = ? 
                           AND ((period_start < ? AND end_time > ?))";

$check_time_lapping = $conn_rjllearning_specific->prepare($sql_check_time_lapping);

$sql_check_duplicate = "SELECT COUNT(*) as duplicate_count FROM timetable 
                        WHERE institution_id = ? 
                        AND branch_id = ? 
                        AND class_id = ? 
                        AND section_id = ? 
                        AND subject_id = ? 
                        AND faculty_id = ? 
                        AND day = ? 
                        AND period_start = ? 
                        AND end_time = ?";

$check_duplicate = $conn_rjllearning_specific->prepare($sql_check_duplicate);

$sql_insert = "INSERT INTO timetable 
               (institution_id, branch_id, faculty_id, academic_session_id, class_id, subject_id, section_id, period_start, end_time, day, type, status, date_created, time_created) 
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'timetable', '1', ?, ?)";

$stmt_insert = $conn_rjllearning_specific->prepare($sql_insert);

foreach ($timetable_info as $temp) {
    $class_id = trim($temp['class_id'] ?? '');
    $section_id = trim($temp['section_id'] ?? '');
    $faculty_id = trim($temp['faculty_id'] ?? '');
    $subject_id = trim($temp['subject_id'] ?? '');
    $day = trim($temp['day'] ?? '');
    $period_start = trim($temp['period_start'] ?? '');
    $end_time = trim($temp['end_time'] ?? '');

    // Validate required fields
    if (!$class_id || !$section_id || !$faculty_id || !$subject_id || !$day || !$period_start || !$end_time) {
        errorreturn("Missing required timetable data.");
    }

    if (!CheckValidateTime($period_start) || !CheckValidateTime($end_time)) {
        errorreturn('Invalid time format.');
    }

    if ($period_start >= $end_time) {
        errorreturn('Invalid time range.');
    }

    // Check for faculty time conflict
    $check_time_lapping->execute([$faculty_id, $academic_id, $institution_id, $branch_id, $day, $end_time, $period_start]);
    $conflict_count = $check_time_lapping->fetch(PDO::FETCH_ASSOC)['conflict_count'] ?? 0;

    if ($conflict_count > 0) {
        errorreturn("Faculty has a time conflict on day $day from $period_start to $end_time.");
    }

    // Check for duplicate timetable entry
    $check_duplicate->execute([$institution_id, $branch_id, $class_id, $section_id, $subject_id, $faculty_id, $day, $period_start, $end_time]);
    $duplicate_count = $check_duplicate->fetch(PDO::FETCH_ASSOC)['duplicate_count'] ?? 0;

    if ($duplicate_count > 0) {
        errorreturn("Duplicate timetable entry detected.");
    }

    // Insert new timetable entry
    $stmt_insert->execute([$institution_id, $branch_id, $faculty_id, $academic_id, $class_id, $subject_id, $section_id, $period_start, $end_time, $day, date('Y-m-d'), time()]);

    if ($stmt_insert->rowCount() == 0) {
        $conn_rjllearning_specific->rollBack();
        errorreturn("Failed to insert timetable.");
    }
}

$conn_rjllearning_specific->commit();
$id = $conn_rjllearning_specific->lastInsertId();


successreturn([ 'successmsg' => "Successfully added timetable."]);
}else{
errorreturn('Wrong function type');
}