<?php
namespace App\Http\Controllers\Warehouse\FixedAssets;

use App\Http\Controllers\Controller;
use App\Models\Warehouse\FixedAssets\FixedAssetReturn;
use App\Models\Warehouse\FixedAssets\FixedAssetReturnItem;
use App\Models\Warehouse\FixedAssets\FixedAsset;
use App\Models\Warehouse\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class FixedAssetReturnController extends Controller
{
    public function __construct()
    {
        $this->middleware('warehouse.access');
        $this->middleware('warehouse.permission:warehouse.fixed-asset-returns.view')->only(['index', 'show', 'print']);
        $this->middleware('warehouse.permission:warehouse.fixed-asset-returns.create')->only(['create', 'store']);
        $this->middleware('warehouse.permission:warehouse.fixed-asset-returns.process')->only(['inspect', 'complete']);
    }

    public function index(Request $request)
    {
        $query = FixedAssetReturn::with(['project', 'returnedBy', 'items'])
            ->latest('created_at');

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('project_id')) {
            $query->where('project_id', $request->project_id);
        }
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('return_number', 'LIKE', "%{$search}%")
                  ->orWhereHas('project', fn($pq) => $pq->where('project_name', 'LIKE', "%{$search}%"));
            });
        }

        $returns = $query->paginate(25)->withQueryString();
        $projects = Project::active()->orderBy('project_name')->get();

        return view('warehouse.fixed-assets.returns.index', compact('returns', 'projects'));
    }

    public function create()
    {
        $projects = Project::active()->orderBy('project_name')->get();
        return view('warehouse.fixed-assets.returns.create', compact('projects'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'project_id' => 'required|exists:projects,id',
            'division_id' => 'nullable|exists:project_divisions,id',
            'return_date' => 'nullable|date',
            'reason' => 'nullable|string|max:500',
            'notes' => 'nullable|string|max:2000',
            'items' => 'required|array|min:1',
            'items.*.fixed_asset_id' => 'required|exists:fixed_assets,id',
            'items.*.condition_on_return' => 'nullable|in:new,good,fair,poor,damaged',
            'items.*.condition_notes' => 'nullable|string|max:500',
            'items.*.needs_maintenance' => 'nullable|boolean',
        ]);

        DB::beginTransaction();
        try {
            $return = FixedAssetReturn::create([
                'project_id' => $request->project_id,
                'division_id' => $request->division_id,
                'return_date' => $request->return_date ?? now(),
                'reason' => $request->reason,
                'notes' => $request->notes,
                'status' => 'draft',
                'returned_by' => Auth::id(),
            ]);

            foreach ($request->items as $itemData) {
                $return->items()->create([
                    'fixed_asset_id' => $itemData['fixed_asset_id'],
                    'condition_on_return' => $itemData['condition_on_return'] ?? null,
                    'condition_notes' => $itemData['condition_notes'] ?? null,
                    'needs_maintenance' => $itemData['needs_maintenance'] ?? false,
                ]);
            }

            DB::commit();

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'data' => $return->load('items'),
                    'message' => 'Return ' . $return->return_number . ' created successfully.'
                ], 201);
            }

            return redirect()->route('warehouse.fixed-assets.returns.show', $return->id)
                ->with('success', 'Return ' . $return->return_number . ' created successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('FixedAssetReturnController@store error: ' . $e->getMessage());
            if ($request->expectsJson()) {
                return response()->json(['success' => false, 'message' => $e->getMessage()], 400);
            }
            return back()->withInput()->with('error', $e->getMessage());
        }
    }

    public function show($id)
    {
        $return = FixedAssetReturn::with([
            'project', 'division', 'returnedBy', 'inspectedBy', 'completedBy',
            'items.fixedAsset.category'
        ])->findOrFail($id);

        return view('warehouse.fixed-assets.returns.show', compact('return'));
    }

    public function inspect(Request $request, $id)
    {
        $return = FixedAssetReturn::with('items')->findOrFail($id);

        if ($return->status !== 'draft') {
            if ($request->expectsJson()) {
                return response()->json(['success' => false, 'message' => 'Only draft returns can be inspected.'], 422);
            }
            return back()->with('error', 'Only draft returns can be inspected.');
        }

        // Optionally update item conditions based on inspection
        if ($request->has('items')) {
            foreach ($request->items as $itemId => $itemData) {
                $item = $return->items()->find($itemId);
                if ($item) {
                    $item->update([
                        'condition_after' => $itemData['condition_after'] ?? $item->condition_on_return,
                        'condition_notes' => $itemData['condition_notes'] ?? $item->condition_notes,
                        'needs_maintenance' => $itemData['needs_maintenance'] ?? $item->needs_maintenance,
                    ]);
                }
            }
        }

        try {
            $return->update([
                'status' => 'inspected',
                'inspected_by' => Auth::id(),
                'inspected_at' => now(),
            ]);

            if ($request->expectsJson()) {
                return response()->json(['success' => true, 'message' => 'Return inspected successfully.']);
            }
            return redirect()->route('warehouse.fixed-assets.returns.show', $return->id)
                ->with('success', 'Return has been inspected.');
        } catch (\Exception $e) {
            \Log::error('FixedAssetReturnController@inspect error: ' . $e->getMessage());
            if ($request->expectsJson()) {
                return response()->json(['success' => false, 'message' => $e->getMessage()], 400);
            }
            return back()->with('error', $e->getMessage());
        }
    }

    public function complete($id)
    {
        $return = FixedAssetReturn::with('items.fixedAsset')->findOrFail($id);

        if (!in_array($return->status, ['draft', 'inspected'])) {
            if (request()->expectsJson()) {
                return response()->json(['success' => false, 'message' => 'This return cannot be completed.'], 422);
            }
            return back()->with('error', 'This return cannot be completed.');
        }

        DB::beginTransaction();
        try {
            $return->complete(Auth::id());
            DB::commit();

            if (request()->expectsJson()) {
                return response()->json(['success' => true, 'message' => 'Return completed. Assets returned to warehouse.']);
            }
            return redirect()->route('warehouse.fixed-assets.returns.show', $return->id)
                ->with('success', 'Return completed. Assets returned to warehouse.');
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('FixedAssetReturnController@complete error: ' . $e->getMessage());
            if (request()->expectsJson()) {
                return response()->json(['success' => false, 'message' => $e->getMessage()], 400);
            }
            return back()->with('error', $e->getMessage());
        }
    }

    public function print($id)
    {
        $return = FixedAssetReturn::with([
            'project', 'division', 'returnedBy', 'inspectedBy', 'completedBy',
            'items.fixedAsset.category'
        ])->findOrFail($id);

        return view('warehouse.fixed-assets.returns.print', compact('return'));
    }

    public function getProjectAssets($projectId)
    {
        $assets = FixedAsset::where('current_project_id', $projectId)
            ->where('lifecycle_status', 'in_use')
            ->with('category')
            ->orderBy('asset_name')
            ->get()
            ->map(function ($asset) {
                return [
                    'id' => $asset->id,
                    'asset_code' => $asset->asset_code,
                    'asset_name' => $asset->asset_name,
                    'asset_tag' => $asset->asset_tag,
                    'serial_number' => $asset->serial_number,
                    'category_name' => $asset->category ? $asset->category->category_name : '-',
                    'condition' => $asset->condition,
                    'text' => $asset->asset_name . ' (' . $asset->asset_code . ')',
                ];
            });

        return response()->json(['success' => true, 'data' => $assets]);
    }
}
