<?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';
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';

require_once $base_path_to_learning_resources . 'lib/common_modules/reminders/function_reminders.php';
require_once $base_path_to_learning_resources . 'lib/cron_jobs/function/function.php';
require_once $base_path_to_learning_resources .'lib/cron_jobs/firebase_notification/fcm_notifications_function.php';
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

$required_fields = ['title', 'description', 'shared_with', 'reminder_date', 'function_type', 'api_signature', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}

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);
}
// either institution id can be all
// or institution id will be specific then branch can be all or specific

$institution_id = isset($postdata['institution_id']) && checkIfIssetAndNotEmpty($postdata['institution_id']) ? ($postdata['institution_id']) : 'all';
if ($institution_id == 'all') {
    $branch_id = 'all';
} else {
    $branch_id = isset($postdata['branch_id']) && checkIfIssetAndNotEmpty($postdata['branch_id']) ? ($postdata['branch_id']) : 'all';
}

$title = ucwords(trim($postdata['title']));
$description = ucwords(trim($postdata['description']));

if (isset($postdata['priority']) and !empty($postdata['priority'])) {
    $priority = trim($postdata['priority']);
} else {
    $priority = 3;
}

// $shared_users_specific = (isset($postdata['shared_users_specific']) and !empty($postdata['shared_users_specific'])) ? ($postdata['shared_users_specific']) : null;

$allowedPriority = ['1', '2', '3'];

// Validate if the input is a valid priority else make it a 3
if (!in_array($priority, $allowedPriority)) {
    $priority = 3;
}

$reminder_date = checkIfIssetAndNotEmpty($postdata['reminder_date']) ? trim($postdata['reminder_date']) : date("Y-m-d");
$reminder_date = date('Y-m-d', strtotime($reminder_date));

// $reminder_time = $postdata['reminder_time'];
$reminder_time = (isset($postdata['reminder_time']) and !empty($postdata['reminder_time'])) ? trim($postdata['reminder_time']) : null;

if ($reminder_time != null) {
    if (!CheckValidateTime($reminder_time)) {
        errorreturn('Invalid reminder time');
    }
} else {
    $reminder_time = date("H:i", time() + 60);
    if (!CheckValidateTime($reminder_time)) {
        errorreturn('Invalid reminder time');
    }
}

$checked_by = (isset($postdata['checked_by']) and !empty($postdata['checked_by'])) ? trim($postdata['checked_by']) : null;

if (isset($postdata['repeat_on']) and !empty($postdata['repeat_on'])) {
    $repeat_on = trim($postdata['repeat_on']);
} else {
    $repeat_on = 'never';
}

if ($repeat_on != null) {
    if ((!in_array($repeat_on, ["never", "daily", "weekly", "weekdays", "weekends", "monthly", "yearly", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]))) {
        errorreturn("Validation failed: $repeat_on is not a valid option for repeat.");
    }
}

// Function to validate specific users based on institution_id 
function validateSpecificUsersReminders($user_ids, $workspace_id, $institution_id, $conn_rjllearning, $branch_id)
{
    $valid_users = [];
    $placeholders = rtrim(str_repeat('?,', count($user_ids)), ',');

    $query = "SELECT id, name, role, branch_id FROM users WHERE id IN ($placeholders) AND workspace_id = ?";

    // Add individual user IDs to the parameters array
    $array_params = array_merge($user_ids, [$workspace_id]);

    // Add the institution condition if applicable
    if ($institution_id != 'all') {
        $query .= " AND institution_id = ?";
        $array_params[] = $institution_id;
    }

    $stmt = $conn_rjllearning->prepare($query);
    $stmt->execute($array_params);


    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $valid_users[] = $row['id'];
        if ($row['role'] != 'admin' and $row['role'] != 'superadmin') {
            // check for branch if specific
            if ($institution_id != "all" and $branch_id != null and $branch_id != "all") {
                if ($row['branch_id'] != $branch_id) {
                    errorreturn($row['name'] . ' does not belong to the selected branch.');
                }
            }
        }
    }
    return $valid_users;
}

$shared_users_specific = null; // Initialize to null before switch block

// Handle the 'shared_with' options
switch ($postdata['shared_with']) {
    case 'all_admins':
    case 'all_principals':
    case 'all_teachers':
        // case 'all_students':
    case 'only_me':
        // 'shared_users_specific' should already be null
        break;

    case 'specific_users':
        if (isset($postdata['shared_users_specific']) && !empty($postdata['shared_users_specific'])) {
            // Validate specific users
            $valid_users = validateSpecificUsersReminders($postdata['shared_users_specific'], $workspace_id, $institution_id, $conn_rjllearning, $branch_id);
            if (!empty($valid_users)) {
                $valid_users_as_strings = array_map('strval', $valid_users);
                $shared_users_specific = json_encode($valid_users_as_strings);
            } else {
                errorreturn("No valid users found for the specified institution");
            }
        } else {
            errorreturn("Please provide specific user IDs.");
        }
        break;

    default:
        errorreturn("Invalid option for shared with.");
}

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

    $last_modified_by = null;
    $last_modified_date = null;

    if (
        strtotime($reminder_date) < strtotime(date("Y-m-d")) ||
        (strtotime($reminder_date) === strtotime(date("Y-m-d")) && strtotime($reminder_time) <= time())
    ) {
        errorreturn("Enter date and time greater than now." . $reminder_time);
    }


    $sql = "INSERT INTO reminders(institution_id, branch_id, userid, title, description, priority, shared_with, shared_users_specific, date_time_created,
     last_modified_date,mark_status, created_by, last_modified_by, reminder_date, reminder_time, checked_by, repeat_on, reference)
            VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute(array(
        $institution_id,
        $branch_id,
        $userid,
        $title,
        $description,
        $priority,
        $postdata['shared_with'],
        $shared_users_specific,
        time(),
        $last_modified_date,
        0,
        $username,
        $last_modified_by,
        $reminder_date,
        $reminder_time,
        null,
        $repeat_on,
        null
    ));

    $id = $conn_rjllearning_specific->lastInsertId();
    $notification_count=sendNotification($conn_rjllearning, $userid,$title, $description );
    
    // Update Mail and SMS count after sending notifications to all students
    updateMailSmsCount($workspace_id, $institution_id, $branch_id, null, null, $notification_count, 'notification', $conn_rjllearning);

    if ($repeat_on != "never") {
        createEntryInRepeatReminders($conn_rjllearning, $workspace_id, $id, $repeat_on, $reminder_date);
    }

    successreturn("Reminder created Successfully");
} else if ($postdata['function_type'] == "alter_reminders") {
    // check if reminder id received or not hen errorreturn
    $id = $postdata['reminder_id'];

    // Check if the reminder exists
    $query = "SELECT id, userid, reminder_date, reminder_time, checked_by, reference FROM reminders WHERE id = ?";
    $stmt = $conn_rjllearning_specific->prepare($query);
    $stmt->execute([$id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        errorreturn("Enter valid reminder id.");
    }

    $originalReminderDate = $result['reminder_date'];
    $originalReminderTime = $result['reminder_time'];
    $existing_reference = $result['reference'];
    $existing_userid = $result['userid'];
    // $checkedby_data = $result['checked_by'] ? json_decode($result['checked_by'], true) : null;

    $sql_role = "SELECT role, institution_id, branch_id FROM users WHERE id = ?";
    $stmt_role = $conn_rjllearning->prepare($sql_role);
    $stmt_role->execute([$existing_userid]);
    $fetch_role = $stmt_role->fetch();
    $creator_role = $fetch_role['role'];
    $existing_institution_id = $fetch_role['institution_id'];
    $existing_branch_id = $fetch_role['branch_id'];

    if ($role == "principal") {
        $sql_principal = "SELECT institution_id, branch_id FROM users WHERE id = ?";
        $stmt_principal = $conn_rjllearning->prepare($sql_principal);
        $stmt_principal->execute([$userid]);
        $fetch_principal = $stmt_principal->fetch();
        $user_institution_id = $fetch_principal['institution_id'];
        $user_branch_id = $fetch_principal['branch_id'];
    }

    $can_edit = false;

    if ($role == "superadmin" || $role == "admin") {
        $can_edit = true;
    } elseif (
        $role == "principal" &&
        ($creator_role == "teacher" || $userid == $existing_userid) &&
        $user_institution_id == $existing_institution_id &&
        $user_branch_id == $existing_branch_id
    ) {
        $can_edit = true;
    } elseif ($role == "teacher" && $userid == $existing_userid) {
        $can_edit = true;
    }

    if (!$can_edit) {
        errorreturn("You do not have permission to edit this reminder.");
    }

    $checkedby_data = $result['checked_by'] ? json_decode($result['checked_by'], true) : [];

    if ($existing_reference != null) {
        $checked_by = filterCheckedBy($conn_rjllearning, $checkedby_data, $postdata, $shared_users_specific, $existing_userid, $role);

        // go and update the original one first (parent reminder)
        $query = "UPDATE reminders SET branch_id = ?, title = ?, description = ?, priority = ?, shared_with = ?, shared_users_specific = ?, 
        last_modified_date = ?, last_modified_by = ?, reminder_date = ?, reminder_time = ?, checked_by = ?, repeat_on = ? WHERE id = ?";
        $conn_rjllearning_specific->prepare($query)->execute([
            $branch_id,
            $title,
            $description,
            $priority,
            $postdata['shared_with'],
            $shared_users_specific,
            time(),
            $username,
            $reminder_date,
            $reminder_time,
            $repeat_on,
            $checked_by,
            $existing_reference
        ]);

        // update common reminder table for start date range and repeat on has changed
        if ($repeat_on != "never") {
            $update_query = "UPDATE repeat_reminders SET workspace_id = ?, repeat_on = ?, date_of_reminder = ? WHERE reminder_id = ?";
            $stmt_update = $conn_rjllearning->prepare($update_query);
            $stmt_update->execute([$workspace_id, $repeat_on, $reminder_date, $existing_reference]);
        } else {
            $deleteQuery = "DELETE FROM repeat_reminders WHERE reminder_id = ?";
            $deleteStmt = $conn_rjllearning->prepare($deleteQuery);
            $deleteStmt->execute([$existing_reference]);
        }

        $query = "SELECT checked_by FROM reminders WHERE reference = ?";
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute([$id]);
        $reminder_result = $stmt->fetchAll();

        foreach ($reminder_result as $reminders) {
            $reference_checkedby_data = $reminders['checked_by'] ? json_decode($reminders['checked_by'], true) : [];
            $checked_by_data = filterCheckedBy($conn_rjllearning, $reference_checkedby_data, $postdata, $shared_users_specific, $existing_userid, $role);

            // If the reminder is a parent, update all child reminders
            $stmt = "UPDATE reminders SET branch_id = ?, title = ?, description = ?, priority = ?, shared_with = ?, shared_users_specific = ?, 
            last_modified_date = ?, last_modified_by = ?, reminder_date = ?, reminder_time = ? , checked_by = ?, repeat_on = ? WHERE reference = ?";
            $conn_rjllearning_specific->prepare($stmt)->execute([
                $branch_id,
                $title,
                $description,
                $priority,
                $postdata['shared_with'],
                $shared_users_specific,
                time(),
                $username,
                $reminder_date,
                $reminder_time,
                $checked_by_data,
                $repeat_on,
                $id
            ]);
        }
    } else {

        $checked_by = filterCheckedBy($conn_rjllearning, $checkedby_data, $postdata, $shared_users_specific, $existing_userid, $role);

        $query = "UPDATE reminders SET branch_id = ?, title = ?, description = ?, priority = ?, shared_with = ?, shared_users_specific = ?, 
         last_modified_date = ?, last_modified_by = ?, reminder_date = ?, reminder_time = ?, checked_by = ?, repeat_on = ? WHERE id = ?";
        $conn_rjllearning_specific->prepare($query)->execute([
            $branch_id,
            $title,
            $description,
            $priority,
            $postdata['shared_with'],
            $shared_users_specific,
            time(),
            $username,
            $reminder_date,
            $reminder_time,
            $checked_by,
            $repeat_on,
            $id
        ]);

        // update common reminder table for start date range and repeat on has changed
        if ($repeat_on != "never") {

            $checkQuery = "SELECT COUNT(*) as count FROM repeat_reminders WHERE reminder_id = ?";
            $stmt_check = $conn_rjllearning->prepare($checkQuery);
            $stmt_check->execute([$id]);
            $result = $stmt_check->fetch(PDO::FETCH_ASSOC);

            if ($result['count'] == 0) {
                createEntryInRepeatReminders($conn_rjllearning, $workspace_id, $id, $repeat_on, $reminder_date);
            } else {
                $update_query = "UPDATE repeat_reminders SET workspace_id = ?, repeat_on = ?, date_of_reminder = ? WHERE reminder_id = ?";
                $stmt_update = $conn_rjllearning->prepare($update_query);
                $stmt_update->execute([$workspace_id, $repeat_on, $reminder_date, $id]);
            }
        } else {
            $deleteQuery = "DELETE FROM repeat_reminders WHERE reminder_id = ?";
            $deleteStmt = $conn_rjllearning->prepare($deleteQuery);
            $deleteStmt->execute([$id]);
        }
    }
     $title .= " update";
     $notification_count=sendNotification($conn_rjllearning, $userid,$title, $description );
    
    // Update Mail and SMS count after sending notifications to all students
    updateMailSmsCount($workspace_id, $institution_id, $branch_id, null, null, $notification_count, 'notification', $conn_rjllearning);
    successreturn("Reminders updated successfully");
} else {
    errorreturn("Invalid Function Type");
}
