<?php
/** @var action_plugin_bez $this */

use \dokuwiki\plugin\bez;

if ($this->model->get_level() < BEZ_AUTH_USER) {
    throw new bez\meta\PermissionDeniedException();
}

if ($this->get_param('tid') == '') {
    header('Location: ' . $this->url('tasks'));
}

/** @var bez\mdl\Task $task */
$task = $this->model->taskFactory->get_one($this->get_param('tid'));
$this->tpl->set('task', $task);
$this->tpl->set('task_comments', $this->model->task_commentFactory->get_from_task($task));
$this->tpl->set('task_programs',  $this->model->task_programFactory->get_all([], 'name'));

if ($this->get_param('action') == 'comment_add') {

    /** @var bez\mdl\Thread_comment $thread_comment */
    $task_comment = $this->model->task_commentFactory->create_object(array('task' => $task));
    $this->model->task_commentFactory->initial_save($task_comment, $_POST);

    $anchor = 'zk'.$task_comment->id;
    $redirect = true;

} elseif ($this->get_param('action') == 'subscribe') {

    $task->set_participant_flags($this->model->user_nick, array('subscribent'));
    $redirect = true;

} elseif ($this->get_param('action') == 'unsubscribe') {

    $task->remove_participant_flags($this->model->user_nick, array('subscribent'));

    $this->add_notification($this->getLang('task_unsubscribed_com'));
    $redirect = true;

} elseif ($this->get_param('action') == 'invite') {
     $client = $_POST['client'];

    $task->invite($client);
    $this->add_notification($this->model->userFactory->get_user_email($client), $this->getLang('invitation_has_been_send'));

    $redirect = true;
} elseif ($this->get_param('action') == 'participant_remove') {
    $user_id = $this->get_param('user_id');
    $task->remove_participant($user_id);

    $name = $this->model->userFactory->get_user_full_name($user_id);
    $notif = sprintf($this->getLang('participant_removed'), $name);
    $this->add_notification($notif);

    $redirect = true;
} elseif ($this->get_param('action') == 'comment_delete') {
    /** @var bez\mdl\Task_comment $task_comment */
    $task_comment = $this->model->task_commentFactory->get_one($this->get_param('zkid'), array('task' => $task));
    $this->model->task_commentFactory->delete($task_comment);

    $redirect = true;
} elseif ($this->get_param('action') == 'comment_edit') {
    /** @var bez\mdl\Task_comment $task_comment */
    $task_comment = $this->model->task_commentFactory->get_one($this->get_param('zkid'), array('task' => $task));

    if(count($_POST) === 0) {
        $this->tpl->set_values($task_comment->get_assoc());
    } else {
        $this->model->task_commentFactory->update_save($task_comment, $_POST);

        $anchor   = 'zk' . $task_comment->id;
        $redirect = true;
    }
} elseif ($this->get_param('action') == 'task_edit') {
    //save
    if (count($_POST) === 0) {
        $this->tpl->set_values($task->get_assoc());
    } else {
        $this->model->taskFactory->update_save($task, $_POST);
        $redirect = true;
    }
} elseif ($this->get_param('action') == 'task_delete') {
    $this->model->taskFactory->delete($task);
    if ($task->thread_id != '') {
        header('Location: ' . $this->url('thread', 'id', $task->thread_id));
    } else {
        header("Location: " . $this->url('tasks'));
    }
} elseif ($this->get_param('action') == 'notify') {
    // Verificar que sea POST con token CSRF valido
    if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !checkSecurityToken()) {
        $this->add_notification('Acción no autorizada.');
        $redirect = true;
    } else {
        // Verificar permiso: al menos vista sobre la tarea
        if ($task->acl_of('id') < BEZ_PERMISSION_VIEW) {
            throw new bez\meta\PermissionDeniedException();
        }

        // Notificacion manual: envia correo completo al creador y responsable
        $recipients = [];
        if ($task->assignee) {
            $recipients[] = $task->assignee;
        }
        if ($task->original_poster && !in_array($task->original_poster, $recipients)) {
            $recipients[] = $task->original_poster;
        }

        if (!empty($recipients)) {
            try {
                $tpl = $this->get_tpl();

                // Nombre del remitente (quien hace clic en Notificar)
                $sender_name = $this->model->userFactory->get_user_full_name($this->model->user_nick);
                $tpl->set('notify_sender', $sender_name ?: $this->model->user_nick);

                // Calcular dias restantes
                $now = new \DateTime(date('Y-m-d'));
                $plan = new \DateTime($task->plan_date);
                $diff = $now->diff($plan);
                $days_remaining = (int)$diff->format('%r%a');

                // Obtener config de prioridad si existe
                $priority_config = null;
                try {
                    $pc = $task->getPriorityConfigForTask();
                    if ($pc) {
                        $priority_config = $pc;
                    }
                } catch (\Exception $e) {
                    // sin config de prioridad, usar valores por defecto
                }

                if ($priority_config) {
                    $tpl->set('priority_bg_color', $priority_config['background_color']);
                    $tpl->set('priority_border_color', $priority_config['border_color']);
                } else {
                    $tpl->set('priority_bg_color', '#e3f2fd');
                    $tpl->set('priority_border_color', '#1976d2');
                }

                $tpl->set('days_remaining', $days_remaining);

                if ($days_remaining < 0) {
                    $msg = 'Esta tarea esta vencida hace ' . abs($days_remaining) . ' dia(s)';
                } elseif ($days_remaining == 0) {
                    $msg = 'Esta tarea vence HOY';
                } else {
                    $msg = 'Esta tarea vence en ' . $days_remaining . ' dia(s)';
                }
                $tpl->set('warning_message', $msg);

                // Compilar estilos
                $less = new \LesserPHP\Lessc();
                $less->addImportDir(DOKU_PLUGIN . 'bez/style/');
                $style = $less->compileFile(DOKU_PLUGIN . 'bez/style/task.less');
                $tpl->set('style', $style);

                // Usar plantilla dedicada para notificacion manual
                $content = $this->bez_tpl_include('mail/task_manual_notify', true);

                // Asunto corto sin tildes para evitar problemas de encoding
                global $conf;
                if ($days_remaining < 0) {
                    $subject_msg = 'Vencida hace ' . abs($days_remaining) . ' dia(s)';
                } elseif ($days_remaining == 0) {
                    $subject_msg = 'Vence HOY';
                } else {
                    $subject_msg = 'Vence en ' . $days_remaining . ' dia(s)';
                }
                $clean_title = strtr($conf['title'], [
                    'á'=>'a','é'=>'e','í'=>'i','ó'=>'o','ú'=>'u',
                    'Á'=>'A','É'=>'E','Í'=>'I','Ó'=>'O','Ú'=>'U',
                    'ñ'=>'n','Ñ'=>'N','ü'=>'u','Ü'=>'U'
                ]);
                $subject = 'Tarea No. ' . $task->id . ' - ' . $subject_msg . ' - ' . $clean_title;

                $sent_to = $task->mail_notify($content, $recipients, [], $subject);

                // Mostrar a quienes se envio
                if (!empty($sent_to)) {
                    $this->add_notification('Notificación enviada a: ' . implode(', ', $sent_to));
                } else {
                    $this->add_notification('No se pudo enviar la notificación (destinatarios sin email o silenciados).');
                }
            } catch (\Exception $e) {
                dbglog('bez notify: error enviando notificacion manual tarea #' . $task->id . ': ' . $e->getMessage());
                $this->add_notification('Error al enviar la notificación: ' . $e->getMessage());
            }
        } else {
            $this->add_notification('No hay destinatarios para notificar (sin creador ni responsable asignado).');
        }

        $redirect = true;
    }

} elseif ($this->get_param('action') == 'pin') {
    $thread_id = $_POST['thread_id'];
    $task->pin($thread_id);
    $redirect = true;
} elseif ($this->get_param('action') == 'unpin') {
    $task->unpin();
    $redirect = true;
}


if (isset($redirect) && $redirect == true) {
    if (isset($anchor)) {
        $anchor = '#'.$anchor;
    } else {
        $anchor = '';
    }
    header("Location: " . $this->url('task', 'tid', $task->id) . $anchor);
}