<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Panel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Validator;

class AdminPanelController extends Controller
{
    public function index(Request $request)
    {
        $category = $request->get('category');

        $panels = Panel::withCount('userPanels')
            ->category($category)
            ->orderBy('sort_order')
            ->orderBy('created_at', 'desc')
            ->get();

        return view('admin.panels.index', compact('panels', 'category'))
            ->with('title', 'Panel Catalog');
    }

    public function create()
    {
        return view('admin.panels.create')
            ->with('title', 'Add New Panel')
            ->with('intervals', Panel::roiIntervals());
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'category' => 'required|in:solar,wall',
            'price' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:5120',
            'roi_percentage' => 'required|numeric|min:0',
            'roi_interval' => 'required|in:' . implode(',', Panel::roiIntervals()),
            'duration' => 'required|integer|min:1',
            'return_capital' => 'nullable|boolean',
            'status' => 'required|in:active,inactive',
            'sort_order' => 'nullable|integer|min:0',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $data = $request->only([
            'name', 'category', 'price', 'description', 'roi_percentage',
            'roi_interval', 'duration', 'status', 'sort_order',
        ]);

        $data['return_capital'] = $request->has('return_capital') ? 1 : 0;
        $data['sort_order'] = $data['sort_order'] ?? 0;

        if ($request->hasFile('image')) {
            $dir = base_path('dash/panels');
            if (!File::isDirectory($dir)) {
                File::makeDirectory($dir, 0755, true);
            }
            $filename = uniqid() . '.' . $request->file('image')->getClientOriginalExtension();
            $request->file('image')->move($dir, $filename);
            $data['image'] = 'panels/' . $filename;
        }

        Panel::create($data);

        return redirect()->route('admin.panels.index')
            ->with('success', 'Panel created successfully.');
    }

    public function edit(Panel $panel)
    {
        return view('admin.panels.edit', compact('panel'))
            ->with('title', 'Edit Panel - ' . $panel->name)
            ->with('intervals', Panel::roiIntervals());
    }

    public function update(Request $request, Panel $panel)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'category' => 'required|in:solar,wall',
            'price' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:5120',
            'roi_percentage' => 'required|numeric|min:0',
            'roi_interval' => 'required|in:' . implode(',', Panel::roiIntervals()),
            'duration' => 'required|integer|min:1',
            'return_capital' => 'nullable|boolean',
            'status' => 'required|in:active,inactive',
            'sort_order' => 'nullable|integer|min:0',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $data = $request->only([
            'name', 'category', 'price', 'description', 'roi_percentage',
            'roi_interval', 'duration', 'status', 'sort_order',
        ]);

        $data['return_capital'] = $request->has('return_capital') ? 1 : 0;
        $data['sort_order'] = $data['sort_order'] ?? 0;

        if ($request->hasFile('image')) {
            if ($panel->image && File::exists(base_path('dash/' . $panel->image))) {
                File::delete(base_path('dash/' . $panel->image));
            }
            $dir = base_path('dash/panels');
            if (!File::isDirectory($dir)) {
                File::makeDirectory($dir, 0755, true);
            }
            $filename = uniqid() . '.' . $request->file('image')->getClientOriginalExtension();
            $request->file('image')->move($dir, $filename);
            $data['image'] = 'panels/' . $filename;
        }

        $panel->update($data);

        return redirect()->route('admin.panels.index')
            ->with('success', 'Panel updated successfully.');
    }

    public function toggleStatus(Panel $panel)
    {
        $panel->update([
            'status' => $panel->status === 'active' ? 'inactive' : 'active',
        ]);

        return redirect()->route('admin.panels.index')
            ->with('success', "Panel {$panel->name} is now {$panel->status}.");
    }

    public function destroy(Panel $panel)
    {
        $panel->delete();

        return redirect()->route('admin.panels.index')
            ->with('success', 'Panel deleted successfully.');
    }
}
