<?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";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
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_resources . 'includes/specific_db_config.php';
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';
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);

try {
    // Get current date and day
    $current_date = date('Y-m-d');
    $current_day = date('D');

    // Mark cronjob as running
    $updateQuery = "UPDATE cronjob_activity SET running_status = ? WHERE activity = ?";
    $stmt = $conn_rjllearning->prepare($updateQuery);
    $stmt->execute([1, 'reminders']);


    // Get all reminders based on reminder_id
    $query = "SELECT * FROM repeat_reminders WHERE date_of_reminder <= CURDATE() ORDER BY workspace_id";
    $stmt = $conn_rjllearning->prepare($query);
    $stmt->execute();
    $reminders = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($reminders)) {
        return "No reminders found.";
    }

    $active_workspace_id = null;
    $conn_rjllearning_specific = null;

    foreach ($reminders as $row) {
        // Switch workspace if needed
        if ($row['workspace_id'] != $active_workspace_id) {
            $active_workspace_id = $row['workspace_id'];

            $dbQuery = "SELECT db_name FROM workspace_database_info WHERE workspace_id = ?";
            $stmt = $conn_rjllearning->prepare($dbQuery);
            $stmt->execute([$active_workspace_id]);
            $db_info = $stmt->fetch(PDO::FETCH_ASSOC);

            $conn_rjllearning_specific = dynamicDbConnection($db_info['db_name']);
        }

        // Fetch reminder details
        $query = "SELECT * FROM reminders WHERE id = ?";
        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute([$row['reminder_id']]);
        $reminder_data = $stmt->fetch(PDO::FETCH_ASSOC);

        if (empty($reminder_data)) {
            continue; // Skip if no reminder data found
        }

        $shared_with = $reminder_data['shared_with']; 
        $shared_users_specific = $reminder_data['shared_users_specific']; 
        $userid = $reminder_data['userid'];

        $reminder_date = $row['date_of_reminder'];
        $reminder_day = date('D', strtotime($reminder_date));
        $repeat_type = $row['repeat_on'];
        $time_of_reminder = $row['time_of_reminder'] ?? '00:00:00';

        $weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
        $weekends = ['Sat', 'Sun'];
        $should_remind = false;

        switch ($repeat_type) {
            case 'daily':
                $should_remind = strtotime($reminder_date) <= strtotime($current_date);
                break;
            case 'weekly':
                $should_remind = ($current_day == $reminder_day) && (strtotime($reminder_date) <= strtotime($current_date));
                break;
            case 'weekdays':
                $should_remind = in_array($current_day, $weekdays) && (strtotime($reminder_date) <= strtotime($current_date));
                break;
            case 'weekends':
                $should_remind = in_array($current_day, $weekends) && (strtotime($reminder_date) <= strtotime($current_date));
                break;
            case 'monthly':
                $should_remind = (date('d') == date('d', strtotime($reminder_date))) && (strtotime($reminder_date) <= strtotime($current_date));
                break;
            case 'yearly':
                $should_remind = (date('m-d') == date('m-d', strtotime($reminder_date))) && (strtotime($reminder_date) <= strtotime($current_date));
                break;
        }

        if ($should_remind) {
            sendReminderToUsers($conn_rjllearning, $row['reminder_id'], $shared_with, $shared_users_specific, $userid);
            
            $next_reminder_date = getNextReminderDate($reminder_date, $repeat_type);
            
            $insert_query = "
                INSERT INTO reminders (institution_id, branch_id, userid, title, description, priority, shared_with, 
                    shared_users_specific, date_time_created, created_by, reminder_date, reminder_time, 
                    checked_by, last_modified_by, last_modified_date, repeat_on, reference
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ";
            
            $stmt = $conn_rjllearning_specific->prepare($insert_query);
            $stmt->execute([
                $reminder_data['institution_id'], $reminder_data['branch_id'], $reminder_data['userid'], 
                $reminder_data['title'], $reminder_data['description'], $reminder_data['priority'], 
                $reminder_data['shared_with'], $reminder_data['shared_users_specific'], time(),
                $reminder_data['created_by'], $next_reminder_date, $reminder_data['reminder_time'], 
                null, null, null, $repeat_type, $reminder_data['id']
            ]);
        }
    }
        // Set running_status to 0 in cronjob_activity table for activity == 'reminders'
        $updateQuery = "UPDATE cronjob_activity SET running_status = ? WHERE activity = ?";
        $stmt = $conn_rjllearning->prepare($updateQuery);
        $stmt->execute([0, 'reminders']);
        
        successreturn("Reminders successfully processed and scheduled.");
} catch (Exception $e) {
    // Print error message
     errorreturn($e->getMessage());
}


function sendReminderToUsers($conn_rjllearning, $reminder_id, $shared_with, $shared_users_specific, $user_id) {
    // Prepare the list of users to send the reminder
    $user_ids = [];

    // Prepare an array to store the user details (name, id, etc.)
    $user_details = [];

    if ($shared_with == 'all_admins') {
        // Fetch all admins
        $stmt = $conn_rjllearning->prepare("SELECT id, email, name FROM users WHERE role = 'admin' or 'superadmin'");
        $stmt->execute();
        $admins = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($admins as $admin) {
            $user_ids[] = $admin['id'];
            $user_details[$admin['id']] = ['name' => $admin['name'], 'email' => $admin['email']];
        }
    } elseif ($shared_with == 'all_principals') {
        // Fetch all principals
        $stmt = $conn_rjllearning->prepare("SELECT id, email, name FROM users WHERE role = 'principal'");
        $stmt->execute();
        $principals = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($principals as $principal) {
            $user_ids[] = $principal['id'];
            $user_details[$principal['id']] = ['name' => $principal['name'], 'email' => $principal['email']];
        }
    } elseif ($shared_with == 'all_teachers') {
        // Fetch all teachers
        $stmt = $conn_rjllearning->prepare("SELECT id, email, name FROM users WHERE role = 'teacher'");
        $stmt->execute();
        $teachers = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($teachers as $teacher) {
            $user_ids[] = $teacher['id'];
            $user_details[$teacher['id']] = ['name' => $teacher['name'], 'email' => $teacher['email']];
        }
    } 

    elseif ($shared_with == 'only_me') {
        // If shared with 'only_me', send to the creator of the reminder (user_id)
        $user_ids[] = $user_id;  // Only send to the user who created the reminder
        $stmt = $conn_rjllearning->prepare("SELECT id, email, name FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            $user_details[$user['id']] = ['name' => $user['name'], 'email' => $user['email']];
        }
    } elseif ($shared_users_specific) {
        // If there are specific users, add them to the list
        $specific_users = json_decode($shared_users_specific); // Decode the JSON array

        foreach ($specific_users as $specific_user_id) {
            $user_ids[] = $specific_user_id;

            // Fetch user details (name, email, etc.) for each specific user
            $stmt = $conn_rjllearning->prepare("SELECT id, email, name FROM users WHERE id = ?");
            $stmt->execute([$specific_user_id]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user) {
                $user_details[$user['id']] = ['name' => $user['name'], 'email' => $user['email']];
            }
        }
    }

    // Also add the creator of the reminder to the list if not already included
    if (!in_array($user_id, $user_ids)) {
        $user_ids[] = $user_id;
        $stmt = $conn_rjllearning->prepare("SELECT id, email, name FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            $user_details[$user['id']] = ['name' => $user['name'], 'email' => $user['email']];
        }
    }

    // Send reminder to each user
    foreach ($user_ids as $user_id) {
        // Get user data from the user_details array
        $user = $user_details[$user_id];

        // Send reminder email (or use other methods like SMS)
        if ($user) {
            $email = $user['email'];
            $subject = "Reminder: Reminder #$reminder_id";
            $message = "Hello " . $user['name'] . ",\n\nThis is a reminder for your task #$reminder_id scheduled for today.";
            sendNotification($conn_rjllearning, $user_id, $subject, $message, $redirectType = null, $redirectId = null);
            // mail($email, $subject, $message);  // Use appropriate mailer in production
        }
    }
}

function getNextReminderDate($current_date, $repeat_type) {
    $next_date = null;

    switch ($repeat_type) {
        case 'daily':
            $next_date = date('Y-m-d', strtotime($current_date . ' +1 day'));
            break;
        case 'weekly':
            $next_date = date('Y-m-d', strtotime($current_date . ' +7 days'));
            break;
        case 'monthly':
            $next_date = date('Y-m-d', strtotime($current_date . ' +1 month'));
            break;
        case 'yearly':
            $next_date = date('Y-m-d', strtotime($current_date . ' +1 year'));
            break;
        case 'weekdays':
            // Get the next weekday (skip weekends)
            $next_date = strtotime($current_date . ' +1 day');
            while (date('N', $next_date) >= 6) { // 6 = Saturday, 7 = Sunday
                $next_date = strtotime('+1 day', $next_date);
            }
            $next_date = date('Y-m-d', $next_date);
            break;
        case 'weekends':
            // Get the next weekend day (Saturday or Sunday)
            $day_of_week = date('N', strtotime($current_date));
            if ($day_of_week == 6) { // If today is Saturday, next is Sunday
                $next_date = date('Y-m-d', strtotime($current_date . ' +1 day'));
            } elseif ($day_of_week < 6) { // If today is a weekday, move to next Saturday
                $next_date = date('Y-m-d', strtotime('next Saturday', strtotime($current_date)));
            } else { // If today is Sunday, move to next Saturday
                $next_date = date('Y-m-d', strtotime('next Saturday', strtotime($current_date)));
            }
            break;
    }

    return $next_date;
}


