<?php
declare(strict_types=1);

namespace App\Models;

use App\Lib\Database;
use App\Util\{Helper};
use App\Helpers\{DateTime, FileHandler};
use App\Models\Uploads;

class StatusUpdates
{
    protected $db;
    protected Helper $helper;
    private string $tableName = 'zoop_updates';
    public static $uploadDirectory = UPLOADS['public_dir'] . '/status';
    public static $publicDirectory = UPLOADS['public'] . '/status';
    public static $defaultImages = 'images/';
    public static $defaultVideos = 'videos/';
    public static $compressedImages = 'compressed-images/';
    public static $compressedVideos = 'compressed-videos/';
    public static $expireAt = 60 * 60 * 24; // expire at 24 hours timestamp

    public function __construct()
    {
        $this->db = Database::connectDB();
        $this->helper = new Helper;
    }

    public function checkStatusBarDevice(string $device)
    {
        $stmt = $this->db->query("SELECT * FROM _status WHERE user_device = ?", $device);
        return  $stmt->rowCount();
    }

    public function saveStatusBar($device, $data)
    {
        if(!$this->checkStatusBarDevice($device)){
            // TODO: save to db
            $this->db->query("INSERT INTO _status", [
                "id" => NULL,
                "user_device" => $device,
                "user_data" => $data
            ]);

            return $this->db->getInsertId();
        }

        return true;
    }

    public function getById(int $updateId)
    {
        $query = "SELECT * FROM {$this->tableName} WHERE update_id = ? LIMIT 1";
        $stmt = $this->db->fetch($query, $updateId);
    }

    public function getAllByRestaurant(int $restaurantId, string $selection = '*', int $limit = null, int $offset = null)
    {
        $query = "SELECT {$selection} FROM {$this->tableName} WHERE owner_id = ? ORDER BY created_at DESC";
        if (!is_null($limit)) {
            $query .= " LIMIT " . intval($limit);

            if (!is_null($offset)) {
                $query .= " OFFSET " . intval($offset);
            }
        }
        $stmt = $this->db->fetchAll($query, $restaurantId);
        return $stmt;
    }

    public function getByExpired(int $limit = null, int $offset = null)
    {
        $query = "SELECT * FROM {$this->tableName} WHERE expire_at < NOW() ORDER BY created_at DESC";
        if (!is_null($limit)) {
            $query .= " LIMIT " . intval($limit);

            if (!is_null($offset)) {
                $query .= " OFFSET " . intval($offset);
            }
        }
        $stmt = $this->db->fetchAll($query);
        return $stmt;
    }

    public function getByRestaurantExpired(int $restaurantId, int $limit = null, int $offset = null)
    {
        $query = "SELECT * FROM {$this->tableName} WHERE (owner_id = ? AND update_owner = 'restaurant') AND expire_at < NOW() ORDER BY created_at DESC";
        if (!is_null($limit)) {
            $query .= " LIMIT " . intval($limit);

            if (!is_null($offset)) {
                $query .= " OFFSET " . intval($offset);
            }
        }
        $stmt = $this->db->fetchAll($query, $restaurantId);
        return $stmt;
    }

    public function addStatus(string $postedBy, int $owner_id, string $media, string $media_type)
    {
        $statusOriginalImages = $this::$uploadDirectory . '/' . $this::$defaultImages;
        $statusCompressedImages = $this::$uploadDirectory . '/' . $this::$compressedImages;

        $statusOriginalVideos = $this::$uploadDirectory . '/' . $this::$defaultVideos;
        $statusCompressedVideos = $this::$uploadDirectory . '/' . $this::$compressedVideos;
        $mediaName = $_FILES['media']['name'];

        $uploads = new Uploads;
        $statusMedia = mt_rand(1000000, 99999999999) . '.' . pathinfo($mediaName, PATHINFO_EXTENSION);
        $statusFormat = Helper::getFormat($mediaName);

        if($statusFormat == 'image') {
            $uploads->uploadFile($media, $statusOriginalImages, $statusMedia);
            $uploads->convertImageToWebp($statusMedia, $statusOriginalImages, $statusCompressedImages);
        }elseif($statusFormat == 'video') {
            $uploads->uploadFile($media, $statusOriginalVideos, $statusMedia);
        }

        $this->db->query("INSERT INTO {$this->tableName}", [
            "update_id" => NULL,
            "update_owner" => $postedBy,
            "owner_id" => $owner_id,
            "update_media" => $statusMedia,
            "update_type" => $media_type,
            "expire_at" => DateTime::from(\DATENOW)->modifyClone(self::$expireAt)->format('Y-m-d H:i:s'),
        ]);

        return $this->db->getInsertId();
    }
}
