<?php

namespace Modules\AppManager\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\AppManager\Entities\ManagedScript;
use Modules\AppManager\Entities\License;
use Modules\AppManager\Entities\ActivationLog;
use Illuminate\Support\Str;

class ManagedScriptController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return \Illuminate\Contracts\View\View
     */
    public function index(Request $request)
    {
        $query = ManagedScript::withCount('licenses')->orderBy('name'); // Eager load license count
        if ($request->filled('search')) {
            $searchTerm = $request->input('search');
            $query->where(function ($q) use ($searchTerm) {
                $q->where('name', 'like', "%{$searchTerm}%")
                  ->orWhere('slug', 'like', "%{$searchTerm}%")
                  ->orWhere('description', 'like', "%{$searchTerm}%");
            });
        }
        $scripts = $query->paginate(15)->withQueryString();

        // New Stats Data
        $totalScriptsCount = ManagedScript::count();
        $totalLicensesCount = License::count();
        $recentSuccessfulActivationsCount = ActivationLog::where('status', 'success')
                                               ->where('activated_at', '>=', now()->subDays(7))
                                               ->count();

        return view('appmanager::admin.managed_scripts.index', compact(
            'scripts',
            'totalScriptsCount',
            'totalLicensesCount',
            'recentSuccessfulActivationsCount'
        ));
    }

    /**
     * Show the form for creating a new resource.
     * @return \Illuminate\Contracts\View\View
     */
    public function create()
    {
        $statuses = ['development' => 'Development', 'active' => 'Active', 'beta' => 'Beta', 'deprecated' => 'Deprecated', 'archived' => 'Archived'];
        return view('appmanager::admin.managed_scripts.create', compact('statuses'));
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:am_managed_scripts,name',
            'slug' => 'nullable|string|max:255|unique:am_managed_scripts,slug',
            'current_version' => 'required|string|max:50',
            'description' => 'nullable|string',
            'changelog' => 'nullable|string',
            'is_boilerplate_core' => 'boolean',
            'status' => 'required|in:development,active,beta,deprecated,archived',
            'envato_item_id' => 'nullable|string|max:50', // Add validation
        ]);

        $data = $request->all();
        $data['slug'] = $request->input('slug') ?: Str::slug($request->input('name'));
        $data['is_boilerplate_core'] = $request->has('is_boilerplate_core');

        ManagedScript::create($data);

        return redirect()->route('admin.appmanager.scripts.index')
                         ->with('success', 'Managed script created successfully.');
    }

    /**
     * Display the specified resource.
     * @param ManagedScript $script
     * @return \Illuminate\Contracts\View\View
     */
    public function show(ManagedScript $script)
    {
        // Typically, for admin, edit is more common than show.
        // You might want to show associated files or licenses here.
        return view('appmanager::admin.managed_scripts.show', compact('script'));
    }

    /**
     * Show the form for editing the specified resource.
     * @param ManagedScript $script
     * @return \Illuminate\Contracts\View\View
     */
    public function edit(ManagedScript $script)
    {
        $statuses = ['development' => 'Development', 'active' => 'Active', 'beta' => 'Beta', 'deprecated' => 'Deprecated', 'archived' => 'Archived'];
        return view('appmanager::admin.managed_scripts.edit', compact('script', 'statuses'));
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param ManagedScript $script
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, ManagedScript $script)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:am_managed_scripts,name,' . $script->id,
            'slug' => 'nullable|string|max:255|unique:am_managed_scripts,slug,' . $script->id,
            'current_version' => 'required|string|max:50',
            'description' => 'nullable|string',
            'changelog' => 'nullable|string',
            'is_boilerplate_core' => 'boolean',
            'status' => 'required|in:development,active,beta,deprecated,archived',
            'envato_item_id' => 'nullable|string|max:50', // Add validation
        ]);

        $data = $request->all();
        $data['slug'] = $request->input('slug') ?: Str::slug($request->input('name'));
        $data['is_boilerplate_core'] = $request->has('is_boilerplate_core');

        $script->update($data);

        return redirect()->route('admin.appmanager.scripts.index')
                         ->with('success', 'Managed script updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     * @param ManagedScript $script
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(ManagedScript $script)
    {
        // Consider what happens to associated licenses and files.
        // Soft delete or prevent deletion if dependencies exist?
        $script->delete();
        return redirect()->route('admin.appmanager.scripts.index')
                         ->with('success', 'Managed script deleted successfully.');
    }
}