<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use App\Models\Loan;
use App\Models\Sparepart;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class LoanController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        // Default Filters
        $startDate = $request->input('start_date', now()->subDays(30)->format('Y-m-d'));
        $endDate = $request->input('end_date', now()->format('Y-m-d'));
        $status = $request->input('status', 'borrowed');

        if ($request->ajax()) {
            // Eager load with soft deletes to showing history even if master data is deleted
            $loans = Loan::with(['employee' => function ($query) {
                $query->withTrashed();
            }, 'sparepart' => function ($query) {
                $query->withTrashed();
            }])
                ->whereDate('borrowed_at', '>=', $startDate)
                ->whereDate('borrowed_at', '<=', $endDate);

            if ($status != 'all') {
                $loans->where('status', $status);
            }

            $loans->latest();

            return DataTables::of($loans)
                ->addIndexColumn()
                ->editColumn('borrowed_at', function ($row) {
                    if ($row->borrowed_at) {
                        return '<div>' . $row->borrowed_at->format('d-m-Y') . '</div>' .
                               '<div class="text-xs text-gray-500">' . $row->borrowed_at->format('H:i') . '</div>';
                    }
                    return '-';
                })
                ->editColumn('returned_at', function ($row) {
                    if ($row->returned_at) {
                        return '<div>' . $row->returned_at->format('d-m-Y') . '</div>' .
                               '<div class="text-xs text-gray-500">' . $row->returned_at->format('H:i') . '</div>';
                    }
                    return '-';
                })
                ->editColumn('status', function ($row) {
                    $status = strtolower($row->status);
                    if ($status == 'borrowed') {
                        return '<span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded" style="background-color: #eab308; color: white;">Dipinjam</span>';
                    } elseif ($status == 'returned') {
                        return '<span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded" style="background-color: #22c55e; color: white;">Dikembalikan</span>';
                    }
                    return '<span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded" style="background-color: #6b7280; color: white;">' . ucfirst($status) . '</span>';
                })
                ->addColumn('action', function ($row) {
                    $btn = '';
                    $status = strtolower($row->status);
                    if ($status == 'borrowed') {
                        $btn .= '<div class="flex gap-2 justify-center">'; // Flex container for alignment
                        $btn .= '<a href="javascript:void(0)" data-id="'.$row->id.'" style="background-color: #10b981; color: white; border-radius: 8px;" class="return-loan inline-block px-3 py-1 bg-green-500 text-white rounded-lg shadow-sm hover:bg-green-600 transition duration-150 ease-in-out font-medium">Kembalikan</a>';
                        $btn .= '<a href="javascript:void(0)" data-id="'.$row->id.'" style="background-color: #ef4444; color: white; border-radius: 8px;" class="delete-loan inline-block px-3 py-1 bg-red-500 text-white rounded-lg shadow-sm hover:bg-red-600 transition duration-150 ease-in-out font-medium">Hapus</a>';
                        $btn .= '</div>';
                    } else {
                        // For returned (or other statuses), show only Delete
                        $btn .= '<div class="flex gap-2 justify-center">';
                        $btn .= '<a href="javascript:void(0)" data-id="'.$row->id.'" style="background-color: #ef4444; color: white; border-radius: 8px;" class="delete-loan inline-block px-3 py-1 bg-red-500 text-white rounded-lg shadow-sm hover:bg-red-600 transition duration-150 ease-in-out font-medium">Hapus</a>';
                        $btn .= '</div>';
                    }
                    return $btn;
                })
                ->rawColumns(['borrowed_at', 'returned_at', 'status', 'action'])
                ->make(true);
        }

        $employees = Employee::orderBy('name')->get();
        $spareparts = Sparepart::where('stock', '>', 0)->orderBy('name')->get();

        return view('loans.index', compact('employees', 'spareparts', 'startDate', 'endDate', 'status'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $employees = Employee::orderBy('name')->get();
        $spareparts = Sparepart::where('stock', '>', 0)->orderBy('name')->get();
        return view('loans.create', compact('employees', 'spareparts'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'employee_id' => 'required|exists:employees,id',
            'sparepart_id' => 'required|exists:spareparts,id',
            'notes' => 'nullable|string',
            'borrowed_at' => 'nullable|date',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => $validator->errors()->first()]);
            }
            return back()->withErrors($validator)->withInput();
        }

        $sparepart = Sparepart::find($request->sparepart_id);

        if ($sparepart->stock <= 0) {
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => 'Stock unavailable for this item.']);
            }
            return back()->withErrors(['sparepart_id' => 'Stock unavailable for this item.']);
        }

        // Decrement stock
        $sparepart->decrement('stock');

        Loan::create([
            'employee_id' => $request->employee_id,
            'sparepart_id' => $request->sparepart_id,
            'borrowed_at' => $request->borrowed_at ? \Carbon\Carbon::parse($request->borrowed_at) : now(),
            'status' => 'borrowed',
            'notes' => $request->notes,
        ]);

        if ($request->ajax()) {
            return response()->json(['success' => true, 'message' => 'Loan created successfully.']);
        }

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

    /**
     * Display the specified resource.
     */
    public function show(Loan $loan)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Loan $loan)
    {
        return response()->json($loan);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Loan $loan)
    {
        // Handle Return
        if ($loan->status == 'returned') {
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => 'Item already returned.']);
            }
            return redirect()->route('loans.index')->with('error', 'Item already returned.');
        }

        $loan->update([
            'returned_at' => $request->returned_at ? \Carbon\Carbon::parse($request->returned_at) : now(),
            'status' => 'returned',
            'notes' => $request->notes // Optional: append notes
        ]);

        // Increment stock
        $loan->sparepart->increment('stock');

        if ($request->ajax()) {
            return response()->json(['success' => true, 'message' => 'Item returned successfully.']);
        }

        return redirect()->route('loans.index')->with('success', 'Item returned successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Loan $loan)
    {
        // Restore stock if the loan was 'borrowed' (active)
        $message = 'Data peminjaman berhasil dihapus.';
        if (strtolower($loan->status) == 'borrowed') {
            $loan->sparepart->increment('stock');
            $message = 'Data peminjaman dibatalkan dan stok dikembalikan.';
        }

        $loan->delete();

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

    /**
     * Get active loans by sparepart code (for QR Return).
     */
    public function getActiveLoansBySparepartCode($code)
    {
        $sparepart = Sparepart::where('code', $code)->first();

        if (!$sparepart) {
            return response()->json([
                'success' => false,
                'message' => 'Suku cadang tidak ditemukan.'
            ], 404);
        }

        $activeLoans = Loan::with('employee')
            ->where('sparepart_id', $sparepart->id)
            ->where('status', 'borrowed')
            ->get()
            ->map(function ($loan) {
                return [
                    'id' => $loan->id,
                    'employee_name' => $loan->employee->name,
                    'borrowed_at_formatted' => $loan->borrowed_at->format('d M Y H:i'),
                    'duration' => $loan->borrowed_at->diffForHumans(),
                ];
            });

        return response()->json([
            'success' => true,
            'sparepart_name' => $sparepart->name,
            'count' => $activeLoans->count(),
            'loans' => $activeLoans
        ]);
    }
}
