<?php

/* Titan © TakfeDev (MKJUEL). All Rights. */

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\JsonResponse;

class SystemController extends Controller
{
    /**
     * Clear various system caches based on type.
     */
    public function clearCache(Request $request): JsonResponse
    {
        $request->validate([
            'type' => 'required|in:app,route,config,view,optimize'
        ]);

        $type = $request->input('type');
        $message = '';

        try {
            switch ($type) {
                case 'app':
                    Artisan::call('cache:clear');
                    $message = 'Application cache cleared!';
                    break;
                case 'route':
                    Artisan::call('route:clear');
                    $message = 'Route cache cleared!';
                    break;
                case 'config':
                    Artisan::call('config:clear');
                    $message = 'Configuration cache cleared!';
                    break;
                case 'view':
                    Artisan::call('view:clear');
                    $message = 'Compiled views cleared!';
                    break;
                case 'optimize':
                    Artisan::call('optimize:clear');
                    $message = 'All caches cleared and system optimized!';
                    break;
            }

            return response()->json(['message' => $message]);

        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to clear cache: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Run Database Migrations.
     */
    public function runMigration(): JsonResponse
    {
        set_time_limit(300); 

        try {
            Artisan::call('migrate', ['--force' => true]);
            $output = Artisan::output();
            Log::info("Manual Migration triggered via Admin Panel:\n" . $output);

            return response()->json([
                'message' => 'Database migration completed successfully.',
                'details' => $output
            ]);

        } catch (\Exception $e) {
            Log::error("Manual Migration Failed: " . $e->getMessage());
            return response()->json(['message' => 'Migration failed: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Create Storage Symlink.
     */
    public function linkStorage(): JsonResponse
    {
        try {
            $linkPath = public_path('storage');

            // 1. Check if the link or folder already exists
            if (file_exists($linkPath) || is_link($linkPath)) {
                
                // 2. Remove the existing link/folder
                
                if (is_link($linkPath)) {
                    @unlink($linkPath); // Deletes Symbolic Link
                } elseif (is_dir($linkPath)) {
                    @rmdir($linkPath); // Deletes Directory/Junction (Windows)
                } else {
                    @unlink($linkPath); // Fallback for file
                }
            }

            // 3. Create the new link fresh
            Artisan::call('storage:link');
            
            return response()->json([
                'message' => 'Old storage link deleted and recreated successfully. Images should now be visible.'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Failed to link storage: ' . $e->getMessage()
            ], 500);
        }
    }
}