<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;

class ClearCacheController extends Controller
{
    public function index()
    {
        $messages = [];
        $errors = [];

        try {
            // Clear application cache
            Artisan::call('cache:clear');
            $messages[] = '✅ تم مسح Application Cache بنجاح';

            // Clear config cache
            Artisan::call('config:clear');
            $messages[] = '✅ تم مسح Config Cache بنجاح';

            // Clear route cache
            try {
                Artisan::call('route:clear');
                $messages[] = '✅ تم مسح Route Cache بنجاح';
            } catch (\Exception $e) {
                // Route cache might not exist
            }

            // Clear view cache
            Artisan::call('view:clear');
            $messages[] = '✅ تم مسح View Cache بنجاح';

            // Clear compiled classes
            try {
                Artisan::call('clear-compiled');
                $messages[] = '✅ تم مسح Compiled Classes بنجاح';
            } catch (\Exception $e) {
                // Might not be needed
            }

            // Clear cache directory manually
            try {
                $cachePath = storage_path('framework/cache/data');
                if (File::exists($cachePath)) {
                    File::cleanDirectory($cachePath);
                    $messages[] = '✅ تم مسح مجلد Cache بنجاح';
                }
            } catch (\Exception $e) {
                $errors[] = '⚠️ تحذير: لم يتم مسح مجلد Cache';
            }

            // Clear views directory
            try {
                $viewsPath = storage_path('framework/views');
                if (File::exists($viewsPath)) {
                    $files = File::files($viewsPath);
                    foreach ($files as $file) {
                        File::delete($file);
                    }
                    $messages[] = '✅ تم مسح Compiled Views بنجاح';
                }
            } catch (\Exception $e) {
                $errors[] = '⚠️ تحذير: لم يتم مسح Compiled Views';
            }

            $success = true;
            $message = implode("\n", $messages);
            if (!empty($errors)) {
                $message .= "\n\n" . implode("\n", $errors);
            }

        } catch (\Exception $e) {
            $success = false;
            $message = '❌ حدث خطأ: ' . $e->getMessage();
        }
        
        return view('clear_cache', [
            'success' => $success,
            'message' => $message ?? 'تم مسح الـ Cache بنجاح'
        ]);
    }
}
