<?php

namespace App\Http\Controllers;

use App\Models\App;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use ZipArchive;

class AppsController extends Controller
{
    public function index()
    {
        $freeApps    = App::where('is_paid', false)->latest()->get();
        $premiumApps = App::where('is_paid', true)->latest()->get();
        return view('apps', compact('freeApps', 'premiumApps'))->with('authUser', Auth::user());
    }

    public function store(Request $request)
    {
        $request->validate([
            'app_key'      => ['required', 'string', 'max:100', 'unique:apps,app_key', 'regex:/^[a-z0-9_]+$/'],
            'display_name' => ['required', 'string', 'max:255'],
            'description'  => ['nullable', 'string'],
            'icon'         => ['nullable', 'string', 'max:100'],
            'color'        => ['nullable', 'string', 'max:20'],
            'category'     => ['nullable', 'string', 'max:100'],
            'page_link'    => ['nullable', 'string', 'max:255'],
            'is_paid'      => ['nullable', 'boolean'],
            'price'        => ['nullable', 'numeric', 'min:0'],
            'currency'     => ['nullable', 'string', 'max:10'],
        ]);

        App::create([
            'app_key'      => $request->app_key,
            'display_name' => $request->display_name,
            'description'  => $request->description,
            'icon'         => $request->icon         ?: 'fas fa-puzzle-piece',
            'color'        => $request->color        ?: '#6d7175',
            'category'     => $request->category,
            'page_link'    => $request->page_link,
            'is_paid'      => $request->boolean('is_paid'),
            'price'        => $request->price        ?? 0,
            'currency'     => $request->currency     ?: 'USD',
            'is_active'    => false, // inactive until module is uploaded
        ]);

        return redirect()->route('apps')->with('success', 'App created. Upload a module ZIP to activate it.');
    }

    public function destroy(App $app)
    {
        // Remove module folder if exists
        $modulePath = base_path('modules/' . $app->app_key);
        if (is_dir($modulePath)) {
            $this->deleteDirectory($modulePath);
        }
        $app->delete();
        return redirect()->route('apps')->with('success', 'App deleted.');
    }

    public function toggle(App $app)
    {
        // Prevent activation if module is not installed
        if (!$app->is_active) {
            $modulePath = base_path('modules/' . $app->app_key);
            if (!is_dir($modulePath)) {
                return redirect()->route('apps')->with('error', 'Cannot activate "' . $app->display_name . '" — module not installed. Upload the module ZIP first.');
            }
        }

        $app->update(['is_active' => !$app->is_active]);
        return redirect()->route('apps')->with('success', 'App status updated.');
    }

    public function uploadModule(Request $request, App $app)
    {
        $request->validate([
            'module_zip' => ['required', 'file', 'mimes:zip', 'max:51200'], // 50 MB
        ]);

        $modulePath = base_path('modules/' . $app->app_key);

        $zip = new ZipArchive();
        if ($zip->open($request->file('module_zip')->getPathname()) === true) {
            // Remove old module contents before extracting fresh copy
            if (is_dir($modulePath)) {
                $this->deleteDirectory($modulePath);
            }
            mkdir($modulePath, 0755, true);
            $zip->extractTo($modulePath);
            $zip->close();
            return redirect()->route('apps')->with('success', 'Module for "' . $app->display_name . '" installed successfully. You can now activate it.');
        }

        return redirect()->route('apps')->with('error', 'Could not open ZIP file. Please try again.');
    }

    // ── Helpers ──────────────────────────────────────────────────────────────

    private function deleteDirectory(string $path): void
    {
        if (!is_dir($path)) return;
        $items = array_diff(scandir($path), ['.', '..']);
        foreach ($items as $item) {
            $full = $path . DIRECTORY_SEPARATOR . $item;
            is_dir($full) ? $this->deleteDirectory($full) : unlink($full);
        }
        rmdir($path);
    }
}
