<?php
/**
 * app/plugins/notifications/models/notification.php
 *
 * This class is used for the manipulation of the notifications database table.
 *
 * @package TP Notifications
 * @version 5.0.1
 * @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\TheTempusProject as App;
use TheTempusProject\Houdini\Classes\Views;
use TheTempusProject\Canary\Classes\CustomException;

class Notification extends DatabaseModel {
    public $tableName = 'notifications';
    public $databaseMatrix = [
        [ 'notification', 'text', '' ],
        [ 'origin', 'varchar', '128' ],
        [ 'userID', 'int', '11' ],
        [ 'createdAt', 'int', '11' ],
        [ 'expiresAt', 'int', '11' ],
        [ 'deletedAt', 'int', '11' ],
        [ 'seenAt', 'int', '11' ],
    ];

    public function getUnreadCount( $userID ) {
        $result = self::$db->get(
            $this->tableName,
            [
                'userID', '=', $userID,
                'AND',
                'deletedAt', '=', '0',
                'AND',
                'seenAt', '=', '0',
                'AND',
                'expiresAt', '<', time(),
            ]
        );
        return $result->count();
    }

    public function create( $notification, $origin, $userID, $expiresAt = '0', $deletedAt = '0', $seenAt = '0' ) {
        $fields = [
            'notification' => $notification,
            'origin' => $origin,
            'userID' => $userID,
            'createdAt' => time(),
            'expiresAt' => $expiresAt,
            'deletedAt' => $deletedAt,
            'seenAt' => $seenAt,
        ];
        if ( !self::$db->insert( $this->tableName, $fields ) ) {
            Debug::info( 'Events::create - failed to insert to db' );
            return false;
        }
        return self::$db->lastId();
    }

    public function getByUser( $limit = 0 ) {
        $whereClause = [
            'userID', '=', App::$activeUser->ID,
            'AND',
            'deletedAt', '=', '0',
            'AND',
            'expiresAt', '<', time(),
        ];
        if ( empty( $limit ) ) {
            $notifications = self::$db->get( $this->tableName, $whereClause );
        } else {
            $notifications = self::$db->get( $this->tableName, $whereClause, 'ID', 'DESC', [0, $limit] );
        }
        if ( !$notifications->count() ) {
            Debug::info( 'Notification:getByUser No Notifications found' );
            return false;
        }
        return $this->filter( $notifications->results() );
    }

    public function markSeen( $id ) {
        if ( !Check::id( $id ) ) {
            Debug::info( 'Notifications: illegal ID.' );
            return false;
        }
        $fields = [
            'seenAt' => time(),
        ];
        $notification = self::findById( $id );
        if ( ! $notification ) {
            Debug::error( "Notifications: $id not updated" );
            return false;
        }
        if ( !self::$db->update( $this->tableName, $id, $fields ) ) {
            new CustomException( 'notificationUpdate' );
            Debug::error( "Notifications: $id not updated" );
            return false;
        }
        return true;
    }

    public function delete( $id ) {
        if ( !Check::id( $id ) ) {
            Debug::info( 'Notifications: illegal ID.' );
            return false;
        }
        $fields = [
            'deletedAt' => time(),
        ];
        if ( !self::$db->update( $this->tableName, $id, $fields ) ) {
            new CustomException( 'notificationDelete' );
            Debug::error( "Notifications: $id not updated" );
            return false;
        }
        return true;
    }
    
    public function filter( $messageArray, $filters = [] ) {
        $out = [];
        foreach ( $messageArray as $message ) {
            if ( !is_object( $message ) ) {
                $message = $messageArray;
                $end = true;
            }
            if ( $message->seenAt == 0 ) {
                $message->unseenBadge = Views::simpleView( 'notifications.unseenBadge' );
                $message->markReadLink = '<a href="{ROOT_URL}notifications/markRead/'.$message->ID.'" class="btn btn-sm btn-primary"><i class="fa-solid fa-fw fa-envelope-open"></i></a>';
            } else {
                $message->unseenBadge = '';
                $message->markReadLink = '';
            }
            $out[] = (object) $message;
            if ( !empty( $end ) ) {
                $out = $out[0];
                break;
            }
        }
        return $out;
    }
}
