<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Asset;
use App\Models\AssetAssignment;
use Illuminate\Http\Request;

class AssetAssignmentController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'asset_id' => 'required|exists:assets,id',
            'user_id' => 'required|exists:users,id',
            'notes' => 'nullable|string',
        ]);

        $asset = Asset::findOrFail($validated['asset_id']);

        if ($asset->status !== 'available') {
            return back()->with('error', 'Asset is not available for assignment.');
        }

        AssetAssignment::create([
            'asset_id' => $validated['asset_id'],
            'user_id' => $validated['user_id'],
            'assigned_at' => now(),
            'notes' => $validated['notes'],
        ]);

        $asset->update(['status' => 'assigned']);

        return back()->with('success', 'Asset assigned successfully.');
    }

    public function return(Request $request, AssetAssignment $assignment)
    {
        $validated = $request->validate([
            'returned_at' => 'required|date',
            'return_condition' => 'required|in:new,good,damaged,lost',
            'notes' => 'nullable|string',
        ]);

        $assignment->update([
            'returned_at' => $validated['returned_at'],
            'return_condition' => $validated['return_condition'],
            'notes' => $assignment->notes."\nReturn Notes: ".$validated['notes'],
        ]);

        $status = 'available';
        if ($validated['return_condition'] === 'damaged') {
            $status = 'maintenance';
        } elseif ($validated['return_condition'] === 'lost') {
            $status = 'retired';
        }

        $assignment->asset->update([
            'status' => $status,
            'condition' => $validated['return_condition'] === 'lost' ? $assignment->asset->condition : $validated['return_condition'],
        ]);

        return back()->with('success', 'Asset returned successfully.');
    }
}
