<?php

// function deleteAllTimetable($conn_rjllearning_specific, $institution_id, $branch_id, $academic_session_id, $class_id, $section_id)
// {

//     $sql = "DELETE FROM timetable WHERE institution_id = ? AND branch_id = ? AND academic_session_id = ? AND class_id = ? AND section_id= ? and type = ? ";
//     $stmt_count = $conn_rjllearning_specific->prepare($sql);
//     $stmt_count->execute(array($institution_id, $branch_id, $academic_session_id, $class_id, $section_id, 'timetable'));
//     $result_timetable = $stmt_count->rowCount();
//     if ($result_timetable >= 1) {
//         return true;
//     } else {
//         return false;
//     }
// }

function deleteAllTimetable($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $branch_id, $academic_session_id, $class_id, $section_id)
{
    // First get all unique faculty IDs that will be affected
    $sql = "SELECT DISTINCT faculty_id FROM timetable WHERE institution_id = ? AND branch_id = ? 
            AND academic_session_id = ? AND class_id = ? 
            AND section_id = ? AND type = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$institution_id, $branch_id, $academic_session_id, $class_id, $section_id, 'timetable']);
    $facultyIds = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

    // Now delete the timetable entries
    $sql = "DELETE FROM timetable WHERE institution_id = ? AND branch_id = ? AND academic_session_id = ? AND class_id = ? 
            AND section_id = ? AND type = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$institution_id, $branch_id, $academic_session_id, $class_id, $section_id, 'timetable']);
    $result_timetable = $stmt->rowCount();

    // Update timestamps for all affected faculty members
    if ($result_timetable >= 1 && !empty($facultyIds)) {
        foreach ($facultyIds as $facultyId) {
            if (!empty($facultyId)) {
                updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $facultyId);
            }
        }
        return true;
    }
    return false;
}



function compareArrays($array1, $array2)
{
    $differences = [];
    foreach ($array1 as $key => $value) {
        if (!in_array($value, $array2)) {
            $differences[] = $value;
        }
    }
    return $differences;
}

function checkTimetableChanges($conn_rjllearning_specific, $timetable_info, $institution_id, $branch_id, $academic_session_id, $class_id, $section_id)
{

    if ($timetable_info != null and is_array($timetable_info)) {
        $timetable_info = $timetable_info;

        $sql_table = $conn_rjllearning_specific->prepare("SELECT * FROM  timetable WHERE institution_id = ? AND branch_id = ? AND academic_session_id = ?   AND class_id = ? AND section_id = ? and type = ?");
        $sql_table->execute(array($institution_id, $branch_id, $academic_session_id, $class_id, $section_id, 'timetable'));
        $result = $sql_table->fetchAll();
        // print_r($result);die();
        $exisiting_timetable_info = [];
        if (count($result) >= 1) {
            foreach ($result as $rows) {
                $days_array[]  = array("day" => $rows['day'], "faculty_id" => $rows['faculty_id'], "subject_id" => $rows['subject_id']);
            }
            $exisiting_timetable_info[]  = array("period_start" => $result[0]['period_start'], "end_time" => $result[0]['end_time'], "days" => $days_array);
        }
        //$exisiting_timetable_info[]  = array("faculty_id"=>$result[0]['faculty_id'],"subject_id"=>$result[0]['subject_id'],"period_start"=>$result[0]['period_start'],"end_time"=>$result[0]['end_time'],"day"=>unserialize($result[0]['day']));

        $differences = compareArrays($exisiting_timetable_info, $timetable_info);
        //print_r($exisiting_timetable_info);
        // print_r($timetable_info);
        //print_r($differences);

        if (empty($differences)) {
            //  echo 'here';
            return false;
        } else {
            //  echo 'here1';die();
            return true;
        }
    } else {
        if ($timetable_info == null)
            return false;
        else
            return true;
    }
}

function deleteAllFacultyTimetable($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $branch_id, $academic_session_id, $faculty_id)
{

    try {
        $sql = "DELETE FROM timetable WHERE institution_id = ? AND branch_id  = ? AND academic_session_id = ? AND  faculty_id = ? and (type = ? or type = ? or type = ?)";
        $stmt_count = $conn_rjllearning_specific->prepare($sql);
        $stmt_count->execute(array($institution_id, $branch_id, $academic_session_id, $faculty_id, 'faculty_role',  'timetable', 'class_incharge'));
        
        updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
    } catch (Exception $e) {
        errorreturn("Error : " . $e->getMessage());
    }
}

function checkFacultyTimetableChanges($conn_rjllearning_specific, $timetable_info, $institution_id, $branch_id, $academic_session_id, $faculty_id)
{
    if ($timetable_info === null) {
        // If no timetable info is provided, return false as no changes can be checked.
        return false;
    }

    // Fetch existing timetable entries for the faculty member.
    $sql_table = $conn_rjllearning_specific->prepare(
        "SELECT * FROM timetable 
         WHERE institution_id = ? AND branch_id = ? AND academic_session_id = ? AND faculty_id = ? AND type = ?"
    );
    $sql_table->execute(array($institution_id, $branch_id, $academic_session_id, $faculty_id, 'faculty_role'));
    $result = $sql_table->fetchAll();

    $existing_timetable_info = [];

    if (count($result) >= 1) {
        // Prepare existing timetable data in a comparable format.
        foreach ($result as $row) {
            $existing_timetable_info[] = [
                "class_id" => $row['class_id'],
                "section_id" => $row['section_id'],
                "subject_id" => $row['subject_id'],
                "period_start" => $row['period_start'],
                "end_time" => $row['end_time'],
                "day" => (!empty($row['day'])) ? unserialize($row['day']) : [], // Handle empty or null days.
            ];
        }

        // Compare existing timetable with the provided timetable info.
        $differences = compareArrays($existing_timetable_info, $timetable_info);

        // If there are no differences, return false (no changes detected).
        return !empty($differences);
    } else {
        // If no existing timetable entries, check if new timetable info is provided.
        return !empty($timetable_info);
    }
}

function CreateClassIncharge($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $branch_id, $academic_id, $faculty_id, $class_incharge)
{

    foreach ($class_incharge as $data) {
        if(!empty($data)) {
            $class_id = $data['class_id'];
            $section_id = $data['section_id'];
            $sql = "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(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            $stmt =  $conn_rjllearning_specific->prepare($sql);
            $stmt->execute(array($institution_id, $branch_id, $faculty_id, $academic_id, $class_id, NULL, $section_id, NULL, NULL, NULL, 'class_incharge', '1', date('Y-m-d'), time()));
            
            updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
        }
    }
}
