<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\DoorPanelResource;
use App\Models\DoorPanel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;

class DoorPanelController extends Controller
{
    public function index(Request $request)
    {
        $perPage = (int) $request->get('per_page', 50);

        $q = DoorPanel::query()->orderBy('id', 'desc');

        if ($request->filled('search')) {
            $s = trim((string) $request->get('search'));
            $q->where('name', 'like', "%{$s}%");
        }

        $items = $q->paginate($perPage);

        return DoorPanelResource::collection($items);
    }

    /**
     * POST /api/door-panels (multipart supported)
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'  => ['required', 'string', 'max:255'],
            'price' => ['nullable', 'numeric', 'min:0'],
            'image' => ['nullable', 'file', 'mimes:png,jpg,jpeg,webp', 'max:5120'],
        ]);

        $payload = [
            'name'  => $validated['name'],
            'price' => (float) ($validated['price'] ?? 0),
        ];

        if ($request->hasFile('image')) {
            $payload['image_path'] = $request->file('image')->store('door-panels', 'public');
        }

        $item = DoorPanel::create($payload);

        return new DoorPanelResource($item);
    }

    public function show(DoorPanel $door_panel)
    {
        return new DoorPanelResource($door_panel);
    }

    /**
     * PUT /api/door-panels/{id} (multipart supported)
     */
    public function update(Request $request, DoorPanel $door_panel)
    {
        $validated = $request->validate([
            'name'  => ['required', 'string', 'max:255'],
            'price' => ['nullable', 'numeric', 'min:0'],
            'image' => ['nullable', 'file', 'mimes:png,jpg,jpeg,webp', 'max:5120'],
        ]);

        $payload = [
            'name'  => $validated['name'],
            'price' => (float) ($validated['price'] ?? 0),
        ];

        if ($request->hasFile('image')) {
            if (!empty($door_panel->image_path)) {
                Storage::disk('public')->delete($door_panel->image_path);
            }
            $payload['image_path'] = $request->file('image')->store('door-panels', 'public');
        }

        $door_panel->update($payload);

        return new DoorPanelResource($door_panel);
    }

    public function destroy(DoorPanel $door_panel)
    {
        if (!empty($door_panel->image_path)) {
            Storage::disk('public')->delete($door_panel->image_path);
        }

        $door_panel->delete();

        return response()->json(['ok' => true]);
    }
}
