<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class MigrationsController extends Controller
{
    public function index()
    {
        $this->authorize('admin_general_dashboard_show');

        // Get list of migration files
        $migrationPath = database_path('migrations');
        $files = glob($migrationPath . '/*.php');
        
        $migrations = [];
        $migrationTable = 'migrations';
        
        // Get ran migrations from database
        $ranMigrations = [];
        if (Schema::hasTable($migrationTable)) {
            $ranMigrations = DB::table($migrationTable)->pluck('migration')->toArray();
        }
        
        foreach ($files as $file) {
            $fileName = basename($file);
            $migrationName = str_replace('.php', '', $fileName);
            
            $migrations[] = [
                'file' => $fileName,
                'name' => $migrationName,
                'path' => $file,
                'ran' => in_array($migrationName, $ranMigrations),
                'date' => date('Y-m-d H:i:s', filemtime($file))
            ];
        }
        
        // Sort by file name (which includes timestamp)
        usort($migrations, function($a, $b) {
            return strcmp($a['file'], $b['file']);
        });

        $data = [
            'pageTitle' => 'إدارة الجداول (Migrations)',
            'migrations' => $migrations,
            'ranMigrations' => $ranMigrations
        ];

        return view('admin.migrations.index', $data);
    }

    public function run(Request $request)
    {
        $this->authorize('admin_general_dashboard_show');

        $migrationPath = $request->input('path');
        $force = $request->input('force', false);

        try {
            if (!empty($migrationPath)) {
                // Extract filename - could be full path or just filename
                $fileName = basename($migrationPath);
                
                // Run specific migration using relative path
                Artisan::call('migrate', [
                    '--path' => 'database/migrations/' . $fileName,
                    '--force' => $force
                ]);
            } else {
                // Run all pending migrations
                Artisan::call('migrate', [
                    '--force' => $force
                ]);
            }

            $output = Artisan::output();
            
            return response()->json([
                'success' => true,
                'message' => 'تم تشغيل المايجريشن بنجاح',
                'output' => $output
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'حدث خطأ أثناء تشغيل المايجريشن',
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ], 500);
        }
    }

    public function status()
    {
        $this->authorize('admin_general_dashboard_show');

        try {
            Artisan::call('migrate:status');
            $output = Artisan::output();

            return response()->json([
                'success' => true,
                'output' => $output
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
