<?php
/**
 * app/plugins/contact/models/contact.php
 *
 * This class is used for the manipulation of the feedback database table.
 *
 * @todo  make this send a confirmation email
 *
 * @package TP Contact
 * @version 3.0
 * @author  Joey Kimsey <Joey@thetempusproject.com>
 * @link    https://TheTempusProject.com
 * @license https://opensource.org/licenses/MIT [MIT LICENSE]
 */
namespace TheTempusProject\Models;

use TheTempusProject\Bedrock\Functions\Check;
use TheTempusProject\Canary\Bin\Canary as Debug;
use TheTempusProject\Classes\DatabaseModel;
use TheTempusProject\Plugins\Contact as Plugin;

class Contact extends DatabaseModel {
    public $tableName = 'feedback';
    public $databaseMatrix = [
        [ 'name', 'varchar', '128' ],
        [ 'time', 'int', '10' ],
        [ 'email', 'varchar', '128' ],
        [ 'ip', 'varchar', '64' ],
        [ 'feedback', 'text', '' ],
    ];
    public $plugin;

    /**
     * The model constructor.
     */
    public function __construct() {
        parent::__construct();
        $this->plugin = new Plugin;
    }

    /**
     * Saves a contact form to the db.
     *
     * @param  string $name     -the name on the form
     * @param  string $email    -the email provided
     * @param  string $feedback -contents of the feedback form.
     * @return bool
     */
    public function create( $name, $email, $feedback ) {
        if ( !$this->plugin->checkEnabled() ) {
            Debug::info( 'Contact is disabled in the config.' );
            return false;
        }
        $fields = [
            'name' => $name,
            'email' => $email,
            'feedback' => $feedback,
            'time' => time(),
            'ip' => $_SERVER['REMOTE_ADDR'],
        ];
        if ( !self::$db->insert( $this->tableName, $fields ) ) {
            Debug::info( 'Contact::create - failed to insert to db' );
            return false;
        }
        return self::$db->lastId();
    }

    /**
     * Function to clear contact from the DB.
     *
     * @todo    is there a way i could check for success here I'm pretty sure this is just a bad idea?
     * @return bool
     */
    public function clear() {
        if ( empty( self::$log ) ) {
            self::$log = new Log;
        }
        self::$db->delete( $this->tableName, ['ID', '>=', '0'] );
        self::$log->admin( 'Contacts Cleared' );
        Debug::info( 'Contacts Cleared' );
        return true;
    }
}
