<?php

namespace App\Http\Controllers;

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

class UserLoanController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();
        $employee = $user->employee; // Uses the getEmployeeAttribute helper

        if (!$employee) {
             return view('user-loans.no-employee-linked');
        }

        // 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', 'all');

        if ($request->ajax()) {
            $loans = Loan::with(['sparepart' => function ($query) {
                $query->withTrashed();
            }])
                ->where('employee_id', $employee->id) // Filter by logged in employee
                ->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) {
                    return '<div>' . $row->borrowed_at->format('d-m-Y') . '</div>' .
                           '<div class="text-xs text-gray-500">' . $row->borrowed_at->format('H:i') . '</div>';
                })
                ->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">';
                        $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 .= '</div>';
                    }
                    return $btn;
                })
                ->rawColumns(['borrowed_at', 'returned_at', 'status', 'action'])
                ->make(true);
        }

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

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

    public function store(Request $request)
    {
        $user = Auth::user();
        $employee = $user->employee;

        if (!$employee) {
            return response()->json(['success' => false, 'message' => 'Akun Anda tidak terhubung dengan data Karyawan. Hubungi Admin.']);
        }

        $request->validate([
            'sparepart_id' => 'required|exists:spareparts,id',
            'notes' => 'nullable|string',
        ]);

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

        if ($sparepart->stock <= 0) {
            return response()->json(['success' => false, 'message' => 'Stok barang habis.']);
        }

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

        Loan::create([
            'employee_id' => $employee->id,
            'sparepart_id' => $request->sparepart_id,
            'borrowed_at' => now(),
            'status' => 'borrowed',
            'notes' => $request->notes,
        ]);

        return response()->json(['success' => true, 'message' => 'Peminjaman berhasil dicatat.']);
    }

    public function returnItem(Request $request, $id)
    {
        $loan = Loan::find($id);

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

        $user = Auth::user();
        $employee = $user->employee;

        if (!$employee || $loan->employee_id != $employee->id) {
             return response()->json(['success' => false, 'message' => 'Unauthorized.'], 403);
        }

        if ($loan->status == 'returned') {
            return response()->json(['success' => false, 'message' => 'Barang sudah dikembalikan sebelumnya.']);
        }

        $loan->update([
            'returned_at' => now(),
            'status' => 'returned',
        ]);

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

        return response()->json(['success' => true, 'message' => 'Barang berhasil dikembalikan.']);
    }

    public function returnByCode(Request $request)
    {
        $request->validate([
            'code' => 'required|string',
        ]);

        $sparepart = \App\Models\Sparepart::where('code', $request->code)->first();

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

        $user = Auth::user();
        $employee = $user->employee;

        if (!$employee) {
             return response()->json(['success' => false, 'message' => 'Akun tidak terhubung dengan Karyawan.'], 403);
        }

        // Find active loan for this user and sparepart
        $loan = Loan::where('employee_id', $employee->id)
                    ->where('sparepart_id', $sparepart->id)
                    ->where('status', 'borrowed')
                    ->latest()
                    ->first();

        if (!$loan) {
            return response()->json(['success' => false, 'message' => 'Anda tidak sedang meminjam barang ini.']);
        }

        $loan->update([
            'returned_at' => now(),
            'status' => 'returned',
        ]);

        $sparepart->increment('stock');

        return response()->json(['success' => true, 'message' => 'Barang berhasil dikembalikan via Scan.']);
    }
}
