<?php
require_once __DIR__ . '/../../infrastructure/Database.php';
class Video
{
    public static function all($status = false)
    {
        try {
            $db = Database::getConnection();
            $query = "SELECT * FROM videos ORDER BY status DESC,id DESC";
            if($status){
                $query = "SELECT * FROM videos WHERE status = 1 ORDER BY status DESC,id DESC";
            }
            $stmt = $db->prepare($query);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            return false;
        }
    }

    public static function findById(int $id){
        try{
            $db = Database::getConnection();
            $stmt = $db->prepare("SELECT * FROM videos WHERE id = :id");
            $stmt->execute([':id' => $id]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        }catch(PDOException $e){
            return false;
        }
    }

    public static function create($link){
        try{
            $db = Database::getConnection();
            $stmt = $db->prepare("INSERT INTO videos (link) VALUES (:link)");
            $stmt->execute([
                ':link' => $link
            ]);
            return true;
        }catch(PDOException $e){
            return false;
        }
    }

    public static function update($id, $data){
        try{
            $db = Database::getConnection();
            $fields = [];
            $params = [':id'=>$id];
            $allowedFields = ['link','status'];

            foreach($allowedFields as $field){
                if(isset($data[$field])){
                    $fields[] = $field . ' = :' . $field;
                    $params[':' . $field] = $data[$field];
                }
            }

            if(empty($fields)){
                return false;
            }

            $query = "UPDATE videos SET " . implode(', ', $fields) . " WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->execute($params);
            return true;
        }catch(PDOException $e){
            return false;
        }
    }
}