<?php

namespace App\Models;

use App\Database;

class Slot
{
    private $db;
    
    public function __construct()
    {
        $this->db = Database::getInstance();
    }
    
    public function getAll()
    {
        return $this->db->fetchAll("SELECT * FROM slots ORDER BY created_at DESC");
    }
    
    public function getById($id)
    {
        return $this->db->fetchOne("SELECT * FROM slots WHERE id = ?", [$id]);
    }
    
    public function getByProvider($provider)
    {
        return $this->db->fetchAll("SELECT * FROM slots WHERE provider = ? ORDER BY name ASC", [$provider]);
    }
    
    public function create($data)
    {
        $sql = "INSERT INTO slots (name, image, provider, rtp, demo_url) VALUES (?, ?, ?, ?, ?)";
        $params = [
            $data['name'],
            $data['image'] ?? null,
            $data['provider'] ?? null,
            $data['rtp'] ?? null,
            $data['demo_url'] ?? null
        ];
        
        $this->db->execute($sql, $params);
        return $this->db->lastInsertId();
    }
    
    public function update($id, $data)
    {
        $sql = "UPDATE slots SET name = ?, image = ?, provider = ?, rtp = ?, demo_url = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?";
        $params = [
            $data['name'],
            $data['image'] ?? null,
            $data['provider'] ?? null,
            $data['rtp'] ?? null,
            $data['demo_url'] ?? null,
            $id
        ];
        
        return $this->db->execute($sql, $params);
    }
    
    public function delete($id)
    {
        return $this->db->execute("DELETE FROM slots WHERE id = ?", [$id]);
    }
    
    public function exists($name, $excludeId = null)
    {
        if ($excludeId) {
            return $this->db->fetchOne("SELECT id FROM slots WHERE name = ? AND id != ?", [$name, $excludeId]);
        }
        
        return $this->db->fetchOne("SELECT id FROM slots WHERE name = ?", [$name]);
    }
    
    public function getProviders()
    {
        $result = $this->db->fetchAll("SELECT DISTINCT provider FROM slots WHERE provider IS NOT NULL ORDER BY provider ASC");
        return array_column($result, 'provider');
    }
    
    public function search($query, $provider = null)
    {
        $sql = "SELECT * FROM slots WHERE name LIKE ?";
        $params = ["%{$query}%"];
        
        if ($provider) {
            $sql .= " AND provider = ?";
            $params[] = $provider;
        }
        
        $sql .= " ORDER BY name ASC";
        
        return $this->db->fetchAll($sql, $params);
    }
}