<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Vault;
use Illuminate\Http\Request;

class VaultController extends Controller
{
    public function index()
    {
        $vaults = Vault::latest()->get();
        return view('admin.vaults.index', compact('vaults'));
    }

    public function create()
    {
        return view('admin.vaults.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'tracking_number' => 'required|unique:vaults',
            'owner_name' => 'required',
            'next_of_kin' => 'nullable',
            'day_price' => 'numeric',
            'month_price' => 'numeric',
            'date_of_deposit' => 'required|date',
            'category' => 'nullable',
            'items' => 'nullable',
            'weight' => 'nullable|numeric',
            'quantity' => 'integer',
            'total_value' => 'numeric',
            'description' => 'nullable',
            'status' => 'required',
            'image' => 'nullable|image|max:2048',
        ]);

        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('vault_images', 'public');
        }

        Vault::create($data);

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

    public function show(Vault $vault)
    {
        return view('admin.vaults.show', compact('vault'));
    }

    public function edit(Vault $vault)
    {
        return view('admin.vaults.edit', compact('vault'));
    }

    public function update(Request $request, Vault $vault)
    {
        $data = $request->validate([
            'tracking_number' => 'required|unique:vaults,tracking_number,' . $vault->id,
            'owner_name' => 'required',
            'next_of_kin' => 'nullable',
            'day_price' => 'numeric',
            'month_price' => 'numeric',
            'date_of_deposit' => 'required|date',
            'category' => 'nullable',
            'items' => 'nullable',
            'weight' => 'nullable|numeric',
            'quantity' => 'integer',
            'total_value' => 'numeric',
            'description' => 'nullable',
            'status' => 'required',
            'image' => 'nullable|image|max:2048',
        ]);

        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('vault_images', 'public');
        }

        $vault->update($data);

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

    public function destroy(Vault $vault)
    {
        $vault->delete();
        return redirect()->route('admin.vaults.index')->with('success', 'Vault deleted successfully.');
    }
}
