<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Log;

class BackupController extends Controller
{
    public function runBackup()
    {
        try {
            // Jalankan Artisan Command
            Artisan::call('db:backup-sql');

            $backupFileName = Artisan::output();

            return response()->json([
                'success' => true,
                'message' => 'Backup database berhasil.',
                'file' => url('/storage/Laravel/' . trim($backupFileName)),
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal menjalankan backup database: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function getBackupFiles()
    {
        $files = Storage::disk('local')->files('Laravel');

        $backupFiles = [];

        foreach ($files as $file) {
            $filename = basename($file);
            // Mencocokkan pola nama file: nama-tanggal_waktu.sql
            if (preg_match('/^(.*)-(\d{4}-\d{2}-\d{2})_(\d{2}-\d{2}-\d{2})\.sql$/', $filename, $matches)) {
                $backupFiles[] = [
                    'filename' => $filename,                        // 1. Nama asli
                    'name_only' => $matches[1],                     // 2. Nama tanpa tanggal
                    'date' => $matches[2],                          // 3. Tanggal
                    'time' => str_replace('-', ':', $matches[3]),   // 4. Waktu
                    'size' => Storage::disk('local')->size($file),  // 5. Size
                ];
            }
        }

        // Urutkan berdasarkan tanggal dan waktu terbaru (descending)
        usort($backupFiles, function ($a, $b) {
            return strcmp($b['date'] . ' ' . $b['time'], $a['date'] . ' ' . $a['time']);
        });

        return response()->json([
            'success' => true,
            'files' => $backupFiles,
        ]);
    }

    public function downloadBackupFile($fileName)
    {
        try {
            $filePath = 'Laravel/' . $fileName;

            if (!Storage::disk('local')->exists($filePath)) {
                return response()->json([
                    'success' => false,
                    'message' => 'File tidak ditemukan.',
                ], 404);
            }

            return Storage::disk('local')->download($filePath, $fileName, [
                'Content-Type' => 'application/sql',
                'Content-Disposition' => 'attachment; filename=' . $fileName
            ]);
        } catch (\Exception $e) {
            Log::error('Error downloading backup file: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengunduh file: ' . $e->getMessage(),
            ], 500);
        }
    }
    public function deleteBackupFile($fileName)
    {
        try {
            $filePath = 'Laravel/' . $fileName;

            if (!Storage::disk('local')->exists($filePath)) {
                return response()->json([
                    'success' => false,
                    'message' => 'File tidak ditemukan.',
                ], 404);
            }

            if (Storage::disk('local')->delete($filePath)) {
                return response()->json([
                    'success' => true,
                    'message' => 'File backup berhasil dihapus.'
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Gagal menghapus file backup.'
                ], 500);
            }
        } catch (\Exception $e) {
            Log::error('Error deleting backup file: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal menghapus file backup: ' . $e->getMessage(),
            ], 500);
        }
    }
}
