<?php
/**
 * app/plugins/subscribe/controllers/admin/subscriptions.php
 *
 * This is the subscriptions admin controller.
 *
 * @package TP Subscribe
 * @version 5.0.1
 * @author  Joey Kimsey <Joey@thetempusproject.com>
 * @link    https://TheTempusProject.com
 * @license https://opensource.org/licenses/MIT [MIT LICENSE]
 */
namespace TheTempusProject\Controllers\Admin;

use TheTempusProject\Bedrock\Functions\Input;
use TheTempusProject\Bedrock\Functions\Check;
use TheTempusProject\Houdini\Classes\Issues;
use TheTempusProject\Houdini\Classes\Views;
use TheTempusProject\Classes\AdminController;
use TheTempusProject\Models\Subscribe;
use TheTempusProject\Classes\Forms;

class Subscriptions extends AdminController {
    public static $subscribe;

    public function __construct() {
        parent::__construct();
        self::$title = 'Admin - Email Subscribers';
        self::$subscribe = new Subscribe;
    }

    public function delete( $data = null ) {
        if ( $data == null ) {
            if ( Input::exists( 'submit' ) ) {
                $data = Input::post( 'S_' );
            }
        }
        if ( !self::$subscribe->delete( (array) $data ) ) {
            Issues::add( 'error', 'There was an error with your request, please try again.' );
        } else {
            Issues::add( 'success', 'Subscriber removed.' );
        }
        $this->index();
    }

    public function add( $data = null ) {
        if ( !Input::exists( 'submit' ) ) {
            return Views::view( 'subscribe.admin.add' );
        }
        if ( !Forms::check( 'subscribe' ) ) {
            Issues::add( 'error', [ 'There was an error with your request.' => Check::userErrors() ] );
            return $this->index();
        }
        if ( !self::$subscribe->add( Input::post( 'email' ) ) ) {
            Issues::add( 'error', 'There was an error with your request, please try again.' );
            return $this->index();
        }
        Issues::add( 'success', 'Subscriber added.' );
        $this->index();
    }

    public function index( $data = null ) {
        Views::view( 'subscribe.admin.list', self::$subscribe->listPaginated() );
    }
}
