<?php

namespace App\Http\Controllers;

use App\Models\Inventory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class InventoryController extends Controller
{
    /* ===============================
       CREATE PAGE
    =============================== */
    public function create()
    {
        return view('inventory.create');
    }

    /* ===============================
       STORE INVENTORY
    =============================== */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'rm_name'       => 'required|string|max:255',
            'type'          => 'required|string',
            'unit_address'  => 'required|string',

            'state_id'  => 'required|exists:states,id',
            'city_id'   => 'required|exists:cities,id',
            'market_id' => 'required|exists:markets,id',

            'area'  => 'required|numeric',
            'rate'  => 'required|numeric',
              'front_view'    => 'required|image|max:500',
                'left_view'     => 'required|image|max:500',
               'right_view'    => 'required|image|max:500',
              'interior_view' => 'required|image|max:500',

        ]);

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

        $data = $request->except([
            '_token',
            'front_view','left_view','right_view','interior_view'
        ]);

        foreach (['front_view','left_view','right_view','interior_view'] as $img) {
            $data[$img] = $request->file($img)->store('inventory', 'public');
        }

        Inventory::create($data);

        return back()->with('success', 'Inventory Added Successfully');
    }

    /* ===============================
       LIST
    =============================== */
    public function list()
    {
        return Inventory::with(['state','city','market'])
            ->latest()
            ->paginate(15);
    }

    /* ===============================
       SHOW
    =============================== */
    public function show($id)
    {
        return Inventory::with(['state','city','market'])->findOrFail($id);
    }

    /* ===============================
       UPDATE INVENTORY (🔥 FIXED)
    =============================== */
    public function update(Request $request, $id)
    {
        $inventory = Inventory::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'rm_name'       => 'required|string|max:255',
            'type'          => 'required|string',
            'unit_address'  => 'required|string',

            'state_id'  => 'required|exists:states,id',
            'city_id'   => 'required|exists:cities,id',
            'market_id' => 'required|exists:markets,id',

            'area'  => 'required|numeric',
            'rate'  => 'required|numeric',

            'front_view'    => 'nullable|image|max:500',
             'left_view'     => 'nullable|image|max:500',
            'right_view'    => 'nullable|image|max:500',
             'interior_view' => 'nullable|image|max:500',

        ]);

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

        /* UPDATE NORMAL FIELDS */
        $inventory->update(
            $request->except([
                '_token','_method',
                'front_view','left_view','right_view','interior_view'
            ])
        );

        /* UPDATE IMAGES (OPTIONAL) */
        /* UPDATE IMAGES (OPTIONAL) */
foreach (['front_view','left_view','right_view','interior_view'] as $img) {

    if ($request->hasFile($img)) {

        // delete old image if exists
        if ($inventory->$img && Storage::disk('public')->exists($inventory->$img)) {
            Storage::disk('public')->delete($inventory->$img);
        }

        // store new image
        $inventory->$img = $request->file($img)->store('inventory', 'public');
    }
}


        $inventory->save();

        return back()->with('success', 'Inventory Updated Successfully');
    }

    /* ===============================
       DELETE
    =============================== */
    public function destroy($id)
    {
        $inventory = Inventory::findOrFail($id);

        foreach (['front_view','left_view','right_view','interior_view'] as $img) {
            if ($inventory->$img && Storage::disk('public')->exists($inventory->$img)) {
                Storage::disk('public')->delete($inventory->$img);
            }
        }

        $inventory->delete();

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