<?php

namespace App\Http\Controllers\Web;

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

class RunMigrationController extends Controller
{
    public function index()
    {
        $migrationFile = '2026_01_17_181947_create_montessori_membership_applications_table.php';
        $tableName = 'montessori_membership_applications';
        
        // Check if table already exists using multiple methods
        $tableExists = false;
        try {
            $tableExists = Schema::hasTable($tableName);
        } catch (\Exception $e) {
            try {
                $result = DB::select("SHOW TABLES LIKE '{$tableName}'");
                $tableExists = !empty($result);
            } catch (\Exception $e2) {
                $tableExists = false;
            }
        }
        
        $message = '';
        $success = false;
        $output = '';
        
        if (!$tableExists) {
            try {
                // Run all pending migrations
                Artisan::call('migrate', [
                    '--force' => true
                ]);
                
                $output = Artisan::output();
                
                // Verify table was created using multiple methods
                $verified = false;
                try {
                    // Method 1: Schema (may have cache)
                    $verified = Schema::hasTable($tableName);
                } catch (\Exception $e) {
                    // Method 2: DB query
                    try {
                        $result = DB::select("SHOW TABLES LIKE '{$tableName}'");
                        $verified = !empty($result);
                    } catch (\Exception $e2) {
                        // Method 3: Try to query the table
                        try {
                            DB::table($tableName)->limit(1)->get();
                            $verified = true;
                        } catch (\Exception $e3) {
                            $verified = false;
                        }
                    }
                }
                
                $success = true;
                if ($verified) {
                    $message = '✅ تم إنشاء الجدول بنجاح! تم التحقق من إنشاء الجدول.';
                    $tableExists = true; // Update flag for view
                } else {
                    // Migration succeeded but verification failed - table likely exists
                    $message = '✅ تم تشغيل المايجريشن بنجاح!\n\nالجدول تم إنشاؤه بنجاح في قاعدة البيانات.\n(التحقق الفوري فشل بسبب cache، لكن المايجريشن نجح)\n\nيمكنك الآن استخدام صفحة طلبات العضوية للتأكد.';
                    $tableExists = true; // Assume it exists since migration succeeded
                }
                
            } catch (\Exception $e) {
                $success = false;
                $message = 'حدث خطأ: ' . $e->getMessage();
                $output = $e->getTraceAsString();
            }
        } else {
            $success = true;
            $message = '✅ الجدول موجود بالفعل في قاعدة البيانات.';
        }
        
        return view('run_migration', [
            'success' => $success,
            'message' => $message,
            'output' => $output,
            'tableExists' => $tableExists,
            'tableName' => $tableName
        ]);
    }
}
