<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Loan;
use Illuminate\Support\Facades\DB;

/**
 * API Controller for managing Loan resources.
 * 
 * This controller handles RESTful API operations including:
 * - Listing, creating, updating, and deleting records via API
 * - JSON response format for all endpoints
 * - Validation and error handling
 * 
 * @package App\Http\Controllers\Api
 */
class LoanController extends Controller
{
    /**
     * Display a listing of the resource via API.
     * 
     * Returns a JSON response with all non-deleted records.
     * Supports eager loading of relations and custom ordering.
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status and data array
     */
    public function index(Request $request)
    {
        $query = Loan::query();
        $query->with(['Employee']);
        $query->latest();
        $data = $query->whereNull('deleted_at')->get();

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

    /**
     * Store a newly created resource in storage via API.
     * 
     * Validates the request data and creates a new record in the database.
     * Returns JSON response with success status and created record ID.
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status, message, and data
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'client_id' => 'nullable|numeric',
            'employee_id' => 'nullable|integer',
            'amount' => 'nullable|numeric',
            'remaining_amount' => 'nullable|numeric',
            'monthly_deduction' => 'nullable|numeric',
            'issue_date' => 'nullable|date',
            'attachment' => 'required|string|max:255',
            'status' => 'required|string|max:255'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        $table = new Loan();

            $table->client_id = $request->input('client_id');
            $table->employee_id = $request->input('employee_id');
            $table->amount = $request->input('amount');
            $table->remaining_amount = $request->input('remaining_amount');
            $table->monthly_deduction = $request->input('monthly_deduction');
            $table->issue_date = $request->input('issue_date');
            if ($request->hasFile('attachment')) {
                $file = $request->file('attachment');
                $currentDate = now();
                $storagePath = $currentDate->year . '/' . $currentDate->month . '/' . $currentDate->day . '/';
                $filename = uniqid() . '_' . $file->getClientOriginalName();
                $file->move(public_path('images/' . $storagePath), $filename);
                $table->attachment = $storagePath . $filename;
            }
            $table->status = $request->input('status');

        $table->save();
        $max_id = $table->id;




        return response()->json([
            'success' => true,
            'message' => 'Record created successfully',
            'data' => ['id' => $max_id],
        ], 201);
    }

    /**
     * Display the specified resource via API.
     * 
     * Returns a JSON response with the requested record details.
     * Returns 404 if the record is not found or has been deleted.
     * 
     * @param Request $request
     * @param int $id The ID of the resource to retrieve
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status and data, or 404 if not found
     */
    public function show(Request $request, $id)
    {
        $query = Loan::query();
        $query->with(['Employee']);
        $row = $query->whereNull('deleted_at')->find($id);

        if (!$row) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found',
            ], 404);
        }

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

    /**
     * Update the specified resource in storage via API.
     * 
     * Validates the request data and updates an existing record in the database.
     * Returns JSON response with success status and updated record ID.
     * Returns 404 if the record is not found or has been deleted.
     * 
     * @param Request $request
     * @param int $id The ID of the resource to update
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status, message, and data, or 404 if not found
     */
    public function update(Request $request, $id)
    {
        $table = Loan::whereNull('deleted_at')->find($id);

        if (!$table) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found',
            ], 404);
        }

        $validator = \Validator::make($request->all(), [
            'client_id' => 'nullable|numeric',
            'employee_id' => 'nullable|integer',
            'amount' => 'nullable|numeric',
            'remaining_amount' => 'nullable|numeric',
            'monthly_deduction' => 'nullable|numeric',
            'issue_date' => 'nullable|date',
            'attachment' => 'nullable|string|max:255',
            'status' => 'nullable|string|max:255'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }


            $table->client_id = $request->input('client_id');
            $table->employee_id = $request->input('employee_id');
            $table->amount = $request->input('amount');
            $table->remaining_amount = $request->input('remaining_amount');
            $table->monthly_deduction = $request->input('monthly_deduction');
            $table->issue_date = $request->input('issue_date');
            if ($request->hasFile('attachment')) {
                $file = $request->file('attachment');
                $currentDate = now();
                $storagePath = $currentDate->year . '/' . $currentDate->month . '/' . $currentDate->day . '/';
                $filename = uniqid() . '_' . $file->getClientOriginalName();
                $file->move(public_path('images/' . $storagePath), $filename);
                $table->attachment = $storagePath . $filename;
            }
            $table->status = $request->input('status');

        $table->update();





        return response()->json([
            'success' => true,
            'message' => 'Record updated successfully',
            'data' => ['id' => (int) $id],
        ], 200);
    }

    /**
     * Remove the specified resource from storage via API.
     * 
     * Soft deletes the specified record (can be restored later).
     * Returns JSON response with success status.
     * Returns 404 if the record is not found or has been deleted.
     * 
     * @param Request $request
     * @param int $id The ID of the resource to delete
     * @return \Illuminate\Http\JsonResponse Returns JSON with success status and message, or 404 if not found
     */
    public function destroy(Request $request, $id)
    {
        $row = Loan::whereNull('deleted_at')->find($id);

        if (!$row) {
            return response()->json([
                'success' => false,
                'message' => 'Record not found',
            ], 404);
        }

        $row->delete();

        return response()->json([
            'success' => true,
            'message' => 'Record deleted successfully',
        ], 200);
    }
}
