@echo off
REM ============================================================
REM  Medmecs MIS - database backup
REM
REM  Creates a timestamped .sql dump of the medmecs_mis database
REM  into the backups\ folder. Run this regularly (or schedule it)
REM  so the database can be restored quickly if it is ever lost.
REM
REM  Restore later with:
REM     mysql -u root medmecs_mis < backups\medmecs_mis_YYYYMMDD_HHMMSS.sql
REM ============================================================
setlocal EnableDelayedExpansion
cd /d "%~dp0"
title Medmecs MIS Backup
color 0B

REM --- Locate mysqldump.exe ---
set "DUMP_EXE="
where mysqldump.exe >nul 2>&1
if not errorlevel 1 ( set "DUMP_EXE=mysqldump" & goto found )
for %%M in ("C:\xampp\mysql\bin\mysqldump.exe" "C:\xampp8\mysql\bin\mysqldump.exe" "D:\xampp\mysql\bin\mysqldump.exe") do (
    if exist "%%~M" ( set "DUMP_EXE=%%~M" & goto found )
)
color 0C
echo Could not find mysqldump.exe. Make sure XAMPP MySQL is installed.
pause
exit /b 1

:found
if not exist "backups" mkdir "backups"

REM --- Timestamp: YYYYMMDD_HHMMSS ---
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /value') do set "DT=%%I"
set "STAMP=%DT:~0,8%_%DT:~8,6%"
set "OUTFILE=backups\medmecs_mis_%STAMP%.sql"

echo.
echo Backing up medmecs_mis to %OUTFILE% ...
"!DUMP_EXE!" -u root --single-transaction --routines --triggers --default-character-set=utf8mb4 medmecs_mis > "%OUTFILE%" 2>nul

if errorlevel 1 (
    color 0C
    echo Backup FAILED. Is MySQL running and is the database present?
    pause
    exit /b 1
)

for %%A in ("%OUTFILE%") do set "SIZE=%%~zA"
set /a SIZEMB=!SIZE! / 1048576

color 0A
echo.
echo ============================================================
echo   BACKUP COMPLETE
echo ============================================================
echo   File:  %OUTFILE%
echo   Size:  !SIZEMB! MB
echo.
echo   To restore:
echo     "C:\xampp\mysql\bin\mysql.exe" -u root medmecs_mis ^< "%OUTFILE%"
echo.

REM --- Keep only the 10 most recent backups ---
set /a KEEP=10
set /a COUNT=0
for /f "delims=" %%F in ('dir /b /o-d "backups\medmecs_mis_*.sql" 2^>nul') do (
    set /a COUNT+=1
    if !COUNT! GTR !KEEP! del "backups\%%F"
)
echo   Keeping the !KEEP! most recent backups (older ones auto-deleted).
echo.
pause
