<?php
declare(strict_types=1);

namespace App\Models;

use App\Helpers\FileHandler;
use App\Lib\Database;
use App\Models\{UserSession};
use App\Util\{Helper, Locate};
use WebPConvert\WebPConvert;

class Cuisine
{
    protected $db;
    protected Helper $helper;
    private string $tableName = 'restaurant_cuisine';

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

    public function getCuisine(int $cuisineId, string $selection = '*')
    {
        $stmt = $this->db->fetch("SELECT {$selection} FROM {$this->tableName} WHERE cuisine_id = ? LIMIT 1", $cuisineId);
        return $stmt;
    }

    public function existCuisine(int $cuisineId)
    {
        $stmt = $this->db->query("SELECT cuisine_id FROM {$this->tableName} WHERE cuisine_id = ? LIMIT 1", $cuisineId);
        return $stmt->rowCount() > 0;
    }

    public function existCuisineRestaurant(int $cuisineId, int $restaurantId)
    {
        $stmt = $this->db->query("SELECT cuisine_data_id FROM {$this->tableName}_data WHERE cuisine_id = ? AND restaurant_id = ? LIMIT 1", $cuisineId, $restaurantId);
        return $stmt->rowCount() > 0;
    }

    public function getCuisineAll(int $restaurantId)
    {
        $stmt = $this->db->fetchAll("SELECT rc.cuisine_id, rc.cuisine_title,
        (CASE WHEN rcd.restaurant_id IS NOT NULL THEN TRUE ELSE FALSE END) AS is_exist
        FROM {$this->tableName} rc
        LEFT JOIN {$this->tableName}_data rcd ON rc.cuisine_id = rcd.cuisine_id AND rcd.restaurant_id = ? ", $restaurantId);
        return $stmt;
    }

    public function setCuisine(int $cuisine_id, int $restaurant_id, $status): void
    {
        $isExist = $this->existCuisineRestaurant($cuisine_id, $restaurant_id);
        if (!$isExist && $status == true) {
            $this->db->query("INSERT INTO {$this->tableName}_data", [
                "cuisine_data_id" => NULL,
                "cuisine_id" => $cuisine_id,
                "restaurant_id" => $restaurant_id,
            ]);
        }elseif($isExist && $status == false){
            $this->db->query("DELETE FROM {$this->tableName}_data WHERE cuisine_id = ? AND restaurant_id = ?", $cuisine_id, $restaurant_id);
        }
    }
}
