<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Cache;

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

        $data = [
            'pageTitle' => 'مسح الـ Cache'
        ];

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

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

        $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 (if needed)
            try {
                $cachePath = storage_path('framework/cache/data');
                if (File::exists($cachePath)) {
                    File::cleanDirectory($cachePath);
                    $messages[] = '✅ تم مسح مجلد Cache بنجاح';
                }
            } catch (\Exception $e) {
                $errors[] = 'تحذير: لم يتم مسح مجلد Cache: ' . $e->getMessage();
            }

            // 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: ' . $e->getMessage();
            }

        } catch (\Exception $e) {
            $errors[] = 'خطأ عام: ' . $e->getMessage();
        }

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

        return back()->with(['msg' => $message, 'cache_cleared' => true]);
    }

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

        $type = $request->input('type');
        $messages = [];

        try {
            switch ($type) {
                case 'cache':
                    Artisan::call('cache:clear');
                    $messages[] = '✅ تم مسح Application Cache بنجاح';
                    break;

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

                case 'route':
                    try {
                        Artisan::call('route:clear');
                        $messages[] = '✅ تم مسح Route Cache بنجاح';
                    } catch (\Exception $e) {
                        $messages[] = '⚠️ Route Cache غير موجود أو لا يمكن مسحه';
                    }
                    break;

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

                case 'compiled':
                    try {
                        Artisan::call('clear-compiled');
                        $messages[] = '✅ تم مسح Compiled Classes بنجاح';
                    } catch (\Exception $e) {
                        $messages[] = '⚠️ Compiled Classes غير موجودة';
                    }
                    break;

                default:
                    return back()->with(['msg' => 'نوع Cache غير صحيح', 'cache_cleared' => false]);
            }
        } catch (\Exception $e) {
            return back()->with(['msg' => 'حدث خطأ: ' . $e->getMessage(), 'cache_cleared' => false]);
        }

        return back()->with(['msg' => implode("\n", $messages), 'cache_cleared' => true]);
    }
}
