<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreRepaymentRequest;
use App\Http\Requests\UpdateRepaymentRequest;
use App\Http\Resources\RepaymentResource;
use App\Models\Credit;
use App\Models\Repayment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class RepaymentController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $this->authorize('view repayments');

        return RepaymentResource::collection(Repayment::all());
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreRepaymentRequest $request)
    {
        $this->authorize('store repayments');

        $fields = $request->validated();

        if ($request->hasFile('attachment')) {
            $fields['attachment'] = $request->file('attachment')->store('repayments', 'public');
        }

        $credit = Credit::find($fields['credit_id']);

        $fields['lender_id'] = $credit->lender_id;

        $repayment = Repayment::create($fields);

        return response()->json([
            "repayment" => new RepaymentResource($repayment)
        ], 201);
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        // Find repayment by ID
        $repayment = Repayment::find($id);

        if ($repayment) {
            return new RepaymentResource($repayment);
        } else {
            return response()->json(['message' => 'Repayment not found'], 404);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateRepaymentRequest $request, $id)
    {
        $this->authorize('update repayments');

        // Find repayment by ID
        $repayment = Repayment::find($id);

        if (!$repayment) {
            return response()->json(['message' => 'Repayment not found'], 404);
        } elseif ($repayment->is_valid) {
            return response()->json(['message' => 'Cannot update a validated repayment'], 403);
        }

        $fields = $request->validated();

        if ($request->hasFile('attachment')) {
            if ($repayment->attachment) {
                Storage::disk('public')->delete($repayment->attachment);
            }
            $fields['attachment'] = $request->file('attachment')->store('repayments', 'public');
        }

        $repayment->update($fields);

        return response()->json(["repayment" => new RepaymentResource($repayment)], 200);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $this->authorize('delete repayments');

        // Find repayment by ID
        $repayment = Repayment::find($id);

        if (!$repayment) {
            return response()->json(['message' => 'Repayment not found'], 404);
        } elseif ($repayment->is_valid) {
            return response()->json(['message' => 'Cannot delete a validated repayment'], 403);
        } else {
            $repayment->delete();
            return response()->json(['message' => 'Repayment deleted successfully'], 200);
        }
    }

    public function validation($id)
    {
        $this->authorize('valid repayments');

        // Find repayment by ID
        $repayment = Repayment::find($id);

        if (!$repayment) {
            return response()->json(['message' => 'Repayment not found'], 404);
        } elseif ($repayment->is_valid) {
            return response()->json(['error' => 'Repayment is already validated'], 400);
        }

        $repayment->update([
            'is_valid' => true,
            'validation_date' => now(),
        ]);

        return response()->json(["repayment" => new RepaymentResource($repayment)], 200);
    }
}
