<?php
    require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/config.php');
    require_once($_SERVER["DOCUMENT_ROOT"] . "/engine/data/dbconfig.php");
    require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/ws_config.php');

    session_start();
    global $db_connect, $ws_config;

    header('Content-Type: application/json');
    $shop_id = $_GET['shop_id'] ?? null;

    $shopFiles = $db_connect->select("shop_product_files", "*", ["shop_id" => $shop_id, "is_main" => 0]);

    $slides = [];

    foreach ($shopFiles as $file) {

        $thumb = $file["url"]; // по умолчанию для изображений

        if($file["file_type"] === "video"){
            $videoPath = $_SERVER["DOCUMENT_ROOT"] . $file["url"];
            $thumbPath = $_SERVER["DOCUMENT_ROOT"] . '/uploads/thumbs/' . basename($file["url"]) . '.jpg';

            if(!file_exists($thumbPath)){
                // создаём директорию, если нет
                @mkdir(dirname($thumbPath), 0777, true);

                // берём кадр с 7-й секунды
                $cmd = "ffmpeg -i " . escapeshellarg($videoPath) . " -ss 00:00:07 -vframes 1 " . escapeshellarg($thumbPath) . " 2>&1";
                exec($cmd, $output, $return_var);
            }

            $thumb = '/uploads/thumbs/' . basename($file["url"]) . '.jpg';
        }

        $slides[] = [
            "type" => $file["file_type"],
            "src" => $file["url"],
            "thumb" => $thumb,
        ];
    }

    echo json_encode($slides);
