<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\Warehouse;
use App\Services\AuditLogService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class WarehouseController extends Controller
{
    public function index()
    {
        $warehouses = Warehouse::with('branch')->latest()->get();
        $branches = Branch::where('status', 'active')->get();
        return view('settings.warehouses.index', compact('warehouses', 'branches'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'code' => 'required|string|max:50|unique:warehouses',
            'name_en' => 'required|string|max:255',
            'name_ar' => 'nullable|string|max:255',
            'branch_id' => 'nullable|exists:branches,id',
            'type' => 'required|in:main,branch,van,transit,damaged',
            'address' => 'nullable|string',
            'contact_person' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:50',
            'status' => 'required|in:active,inactive',
        ]);

        $warehouse = Warehouse::create($validated);

        AuditLogService::log('WAREHOUSE_CREATED', 'Warehouses', $warehouse->id, null, $warehouse->toArray());

        return redirect()->route('warehouses.index')->with('success', 'Warehouse created successfully.');
    }

    public function update(Request $request, Warehouse $warehouse)
    {
        $validated = $request->validate([
            'code' => ['required', 'string', 'max:50', Rule::unique('warehouses')->ignore($warehouse->id)],
            'name_en' => 'required|string|max:255',
            'name_ar' => 'nullable|string|max:255',
            'branch_id' => 'nullable|exists:branches,id',
            'type' => 'required|in:main,branch,van,transit,damaged',
            'address' => 'nullable|string',
            'contact_person' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:50',
            'status' => 'required|in:active,inactive',
        ]);

        $oldData = $warehouse->toArray();
        $warehouse->update($validated);

        AuditLogService::log('WAREHOUSE_UPDATED', 'Warehouses', $warehouse->id, $oldData, $warehouse->fresh()->toArray());

        return redirect()->route('warehouses.index')->with('success', 'Warehouse updated successfully.');
    }

    public function destroy(Warehouse $warehouse)
    {
        AuditLogService::log('WAREHOUSE_DELETED', 'Warehouses', $warehouse->id, $warehouse->toArray());
        $warehouse->delete();

        return redirect()->route('warehouses.index')->with('success', 'Warehouse deleted successfully.');
    }
}
