@echo off
title Media Download Menu
setlocal EnableDelayedExpansion

:: === Read MD version from "ver" file ===
set "VERSION=Unknown"
if exist "%~dp0ver" (
    for /f "delims=" %%x in (%~dp0ver) do set "VERSION=%%x"
)

:: === Silent auto-update yt-dlp (once per 24h) ===
set "YTDLP=yt-dlp.exe"
set "LASTCHECK=%~dp0ytdlp_lastcheck.txt"

if exist "%YTDLP%" (
    set "DO_CHECK=True"

    if exist "%LASTCHECK%" (
        for /f "delims=" %%A in ('
            powershell -NoProfile -Command ^
            "$f='%LASTCHECK%'; if (Test-Path $f) { ((Get-Date)-(Get-Item $f).LastWriteTime).TotalHours -ge 24 } else { $true }"
        ') do set "DO_CHECK=%%A"
    )

    if /I "!DO_CHECK!"=="True" (
        echo [INFO] Checking for yt-dlp update...
        "%YTDLP%" -U >nul 2>&1
        if !errorlevel! equ 0 (
            echo [INFO] yt-dlp is up to date.
        ) else (
            echo [WARN] yt-dlp update failed.
        )
        (echo Updated on %date% %time%) > "%LASTCHECK%"
    ) else (
        echo [INFO] yt-dlp check skipped (less than 24h since last check)
    )
)

:menu
cls
echo.
echo ================================
echo        MEDIA DOWNLOADER
echo ================================
echo Version: %VERSION%
echo.
echo Select platform and download type:
echo -----------------------------------------
echo [1]  YouTube Complete
echo [2]  YouTube Trim
echo [3]  Facebook Complete
echo [4]  Facebook Trim
echo [5]  TikTok Complete
echo [6]  X (Twitter) Complete
echo [7]  Instagram Complete
echo [8]  Update yt-dlp
echo [9]  Update md
echo [10] Folders
echo [11] Uninstall / Reinstall
echo [0]  Exit
echo -----------------------------------------
set /p "OPTION=Enter your choice (0-11): "

:: Normalize input (remove spaces)
set "OPTION=%OPTION: =%"

if "%OPTION%"=="0"  goto exit
if "%OPTION%"=="1"  goto yt_complete
if "%OPTION%"=="2"  goto yt_trim
if "%OPTION%"=="3"  goto fb_complete
if "%OPTION%"=="4"  goto fb_trim
if "%OPTION%"=="5"  goto tiktok
if "%OPTION%"=="6"  goto x
if "%OPTION%"=="7"  goto insta
if "%OPTION%"=="8"  goto update_ytdlp
if "%OPTION%"=="9"  goto update_md
if "%OPTION%"=="10" goto folders
if "%OPTION%"=="11" goto reinstall

echo.
echo [ERROR] Invalid option! Please enter a number between 0 and 11.
pause
goto menu

:yt_complete
start cmd /c youtube_downloader.bat
goto menu

:yt_trim
start cmd /c youtube_downloader_trim.bat
goto menu

:fb_complete
start cmd /c facebook_downloader.bat
goto menu

:fb_trim
start cmd /c facebook_downloader_trim.bat
goto menu

:tiktok
start cmd /c tiktok_downloader.bat
goto menu

:x
start cmd /c x_downloader.bat
goto menu

:insta
start cmd /c instagram_downloader.bat
goto menu

:update_ytdlp
start cmd /c update_ytdlp.bat
goto menu

:update_md
start cmd /c update_md.bat
goto menu

:folders
start cmd /c folders.bat
goto menu

:reinstall
echo.
echo [INFO] Launching uninstall / reinstall process...
start cmd /c "cd /d %SystemDrive% && install.bat"
exit

:exit
exit
