<?php

class ReminderController extends Controller {
    public function sendOverdueReminders() {
    session_start();

    if ($_SESSION['user_role'] !== 'admin') {
        header("Location: " . BASE_URL . "/LoginController/logout");
        exit;
    }

    $taskModel = $this->model('Task');
    $tasks = $taskModel->getOverdueTasksWithEmails();

    foreach ($tasks as $task) {
        $to = $task['email'];
        $subject = "Overdue Task Reminder: " . $task['title'];
        $message = "
            Hi {$task['user_name']},

            This is a reminder that the task \"{$task['title']}\" assigned to you is overdue.
            Contact: {$task['contact_name']}
            Due Date: {$task['due_date']}
            
            Please log in and update the task.

            Regards,
            CRM System
        ";
        $headers = "From: info@techlutry.co.za";

        mail($to, $subject, $message, $headers);
    }

    echo "Sent reminders to " . count($tasks) . " overdue task(s).";
}

    public function sendOverdueRemindersManual() {
    session_start();
    if ($_SESSION['user_role'] !== 'admin') {
        header("Location: " . BASE_URL . "/LoginController/logout");
        exit;
    }

    $taskModel = $this->model('Task');
    $tasks = $taskModel->getOverdueTasksWithEmails(false); // Only unreminded tasks

    $ccEmails = !empty($_POST['cc_emails']) ? explode(',', $_POST['cc_emails']) : [];
    $ccEmailStr = implode(',', $ccEmails);
    $count = 0;

    foreach ($tasks as $task) {
        $to = $task['email'];
        $subject = "Overdue Task Reminder: " . $task['title'];
        $message = "
            Hi {$task['user_name']},

            This is a reminder that the task \"{$task['title']}\" assigned to you is overdue.
            Contact: {$task['contact_name']}
            Due Date: {$task['due_date']}

            Please log in and update the task.

            Regards,
            CRM System
        ";

        $headers = "From: info@techlutry.co.za\r\n";
        if (!empty($ccEmails)) {
            $headers .= "Cc: " . $ccEmailStr . "\r\n";
        }

        if (mail($to, $subject, $message, $headers)) {
            // ✅ Mark as reminded
            $taskModel->markTaskAsReminded($task['id']);

            // ✅ Log reminder
            $taskModel->logReminder($task['id'], $_SESSION['user_id'], $ccEmailStr);

            $count++;
        }
    }

    $success = "📬 Sent reminders to {$count} overdue task(s).";
    $this->view('reminders/manual', ['success' => $success]);
}




    public function manual() {
    session_start();

    if ($_SESSION['user_role'] !== 'admin') {
        header("Location: " . BASE_URL . "/LoginController/logout");
        exit;
    }

    $taskModel = $this->model('Task');
    $overdueTasks = $taskModel->getOverdueTasksWithEmails();

    $this->view('reminders/manual', [
        'overdueTasks' => $overdueTasks,
        'success' => '',
        'error' => ''
    ]);
}


}
