<?php

namespace Hwapx\Email\Controller\Admin;

use Hwapx\Admin\Controller\Admin\Admin;
use Hwapx\Core\Library\Template as SystemTemplate;
use Hwapx\Core\Library\Validator;
use Hwapx\Core\Library\Web;
use Hwapx\Core\Library\Form;
use HwapX\Admin\Library\Builder\TableBuilder;
use HwapX\Admin\Library\Builder\FormBuilder;
use HwapX\Core\Library\DB\SQL\Mapper;

class Queue extends Admin {
  protected $validator = null;
  protected $logger    = null;
  protected $form = array(
      'name'   => 'Email na fila',
      'table'  => 'admin_email_queue_list',
      'groups' => array(
          'main' => array(
              'legend' => 'Template',
              'fields' =>  array(
                  'subject' => array(
                      'label' => 'Assunto',
                      'type'  => 'text',
                      'rules' => array(
                          'required',
                        )
                    ),
                  'from' => array(
                      'label' => 'Remetente',
                      'type'  => 'text',
                      'rules' => array(
                        )
                    ),
                  'to' => array(
                      'label' => 'Para',
                      'type'  => 'text',
                      'rules' => array(
                          'required'
                        )
                    ),
                  'reply_to' => array(
                      'label' => 'Responder para',
                      'type'  => 'text',
                      'rules' => array(
                        )
                    ),
                  'cc' => array(
                      'label' => 'CC',
                      'type'  => 'text',
                      'rules' => array(
                        )
                    ),
                  'bcc' => array(
                      'label' => 'BCC',
                      'type'  => 'text',
                      'rules' => array(
                        )
                    ),
                  'body' => array(
                      'label' => 'Corpo',
                      'type'  => 'wysiwyg',
                      'rules' => array(
                          'required'
                        )
                    ),
                )
            ),
          'misc' => array(
              'legend' => 'Extra',
              'fields' => array(
                  'template_id'    => array(
                      'label'   => 'Template',
                      'type'    => 'dropdown',
                      'options' => array(
                          '' => '-- Nenhum --',
                        ),
                      'rules'   => array(
                        )
                    ),
                  'account_id'    => array(
                      'label'   => 'Conta',
                      'type'    => 'dropdown',
                      'options' => array(
                          '' => '-- Nenhuma --',
                        ),
                      'rules'   => array(
                        )
                    ),
                  'data' => array(
                      'label' => 'Dados',
                      'type'  => 'textarea',
                      'width'   => 6,
                      'rules' => array(
                        )
                    ),
                  'attachments' => array(
                      'label' => 'Anexos',
                      'type'  => 'textarea',
                      'width'   => 6,
                      'rules' => array(
                        )
                    ),
                  'cancelled_on'    => array(
                      'label'   => 'Cancelado em',
                      'type'    => 'datetime',
                      'rules'   => array(
                        )
                    ),
                  'sent_at'    => array(
                      'label'   => 'Enviado em',
                      'type'    => 'datetime',
                      'rules'   => array(
                        )
                    ),
                    'track'    => array(
                        'label'   => 'Rastrear Leitura',
                        'type'    => 'dropdown',
                        'default' => 0,
                        'options' => array(
                            '0' => 'Não',
                            '1' => 'Sim',
                          ),
                        'rules'   => array(
                            'required'
                          )
                      ),
                  'callback'    => array(
                      'label'   => 'Callback',
                      'type'    => 'text',
                      'rules'   => array(
                        )
                    ),
                )
            ),
          'log' => array(
              'legend' => 'Log',
              'fields' => array(
                  'to_parsed'    => array(
                      'label'   => 'Para (Processado)',
                      'type'    => 'static',
                      'rules'   => array(
                        )
                    ),
                  'subject_parsed'    => array(
                      'label'   => 'Assunto (Processado)',
                      'type'    => 'static',
                      'rules'   => array(
                        )
                    ),
                  'body_parsed' => array(
                      'label'   => 'Mensagem (Processada)',
                      'type'    => 'statichtml',
                      'attributes'   => array(
                          'disabled' => 'disabled',
                          'readonly' => 'readonly',
                        )
                    ),
                  'callback_data' => array(
                      'label'   => 'Callback data',
                      'type'    => 'staticarea',
                      'width'   => 6,
                      'attributes'   => array(
                          'disabled' => 'disabled',
                          'readonly' => 'readonly',
                        )
                    ),
                  'log' => array(
                      'label'   => 'Log',
                      'type'    => 'staticarea',
                      'width'   => 6,
                      'attributes'   => array(
                          'disabled' => 'disabled',
                          'readonly' => 'readonly',
                        )
                    ),
                  'executed_on'    => array(
                      'label'   => 'Executado em',
                      'type'    => 'static',
                    ),
                  'read_count' => array(
                      'label' => 'Quantidade de leituras',
                      'type'  => 'static',
                  ),
                )
            )
        )
    );

  protected $table = array(
      'name'   => 'Emails na Fila',
      'cols'    => array(
          'id'          => '#',
          'from'        => 'Remetente',
          'to'          => 'Destinatário',
          'subject'     => 'Assunto',
          //'account_s'   => 'Conta',
          'sent_at'     => 'Enviado em'
        ),
      'actions' => array(
          array(
              'route'       => 'admin_email_queue_purge',
              'description' => 'Remover enviados',
              'class'       => 'btn-danger',
              'confirm'     => true,
              'role'        => 'hwapx.email.queue_purge'
            ),
          array(
              'route'       => 'admin_email_queue_create',
              'description' => 'Novo',
              'class'       => 'btn-primary',
              'role'        => 'hwapx.email.queue_create'
            )
        ),
      'rowactions' => array(
          array(
              'route'       => 'admin_email_queue_edit',
              'description' => 'Alterar',
              'class'       => 'btn-primary',
              'default'     => true,
              'role'        => 'hwapx.email.queue_edit'
            ),
          array(
              'route'       => 'admin_email_queue_remove',
              'description' => 'Remover',
              'class'       => 'btn-danger',
              'confirm'     => true,
              'role'        => 'hwapx.email.queue_remove'
            )
        ),
      'rowcount'    => true,
      'route'       => 'admin_email_queue_list',
      'legend' => array(
        'default' => 'Pendente',
        'active'  => 'Cancelado',
        'warning' => 'Processando',
        'success' => 'Enviado',
        'info'    => 'Lido',
        'danger'  => 'Falha',
      )
    );

  public function __construct($f3) {
    parent::__construct($f3);

    $db     = $f3->get('db');
    $mapper = new Mapper($db, 'hwapx_email_account');

    foreach ($mapper->find() as $row)
      $this->form['groups']['misc']['fields']['account_id']['options'][$row->id] = $row->description;

    $mapper = new Mapper($db, 'hwapx_email_template');

    foreach ($mapper->find() as $row)
      $this->form['groups']['misc']['fields']['template_id']['options'][$row->id] = $row->description;
  }

	public function index($f3) {
    $this->module->checkRole('hwapx.email.queue_list');

    $db    = $f3->get('db');
    $mapper = new \DB\SQL\Mapper($db, 'hwapx_email_queue');

    $mapper->account_s   = 'SELECT hwapx_email_account.description FROM hwapx_email_account WHERE hwapx_email_account.id = hwapx_email_queue.account_id';

    $this->table['rowcallback'] = function($mapper) use($f3) {
      $data = array();

      if($mapper->sent_at && $mapper->read_count) {
        $data['class'] = 'info';
      } else if($mapper->sent_at) {
        $data['class'] = 'success';
      } else if($mapper->cancelled_on) {
        $data['class'] = 'active';
      } else if($mapper->failed) {
        $data['class'] = 'danger';
      } else if ($mapper->executed_on && !$mapper->sent_at && !$mapper->cancelled_on && !$mapper->failed) {
        $data['class'] = 'warning';
      }

      return $data;
    };

		echo TableBuilder::instance($mapper, $this->table)->render();
	}

  public function create($f3) {
    $this->module->checkRole('hwapx.email.queue_create');

    $db   = $f3->get('db');
    $mapper = new \DB\SQL\Mapper($db, 'hwapx_email_queue');

    echo FormBuilder::instance($mapper, $this->form)->handle();
  }

	public function alter($f3) {
    $this->module->checkRole('hwapx.email.queue_edit');

    $db     = $f3->get('db');
    $mapper = new \DB\SQL\Mapper($db, 'hwapx_email_queue');

    echo FormBuilder::instance($mapper, $this->form)->handle();
	}

  public function remove($f3) {
    $this->module->checkRole('hwapx.email.queue_remove');

    $db     = $f3->get('db');
    $mapper = new \DB\SQL\Mapper($db, 'hwapx_email_queue');

    echo FormBuilder::instance($mapper, $this->form)->delete();
  }

  public function purge($f3) {
    $this->module->checkRole('hwapx.email.queue_purge');
    $db = $f3->get('db');
    $count = $db->exec('DELETE FROM hwapx_email_queue WHERE sent_at IS NOT NULL');
    flash('success', "$count registros foram removidos da fila.");
    $f3->reroute('@admin_email_queue_list');
  }
}
