<?php

namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\CreditDeductable;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Models\CreditsDeductable;
use App\Models\CommitteeApproval;
use App\Models\CreditRequest;

class CreditsDeductableController extends Controller
{
   public function checkClientAndSeed(Request $request)
    {
        $request->validate([
            'client_id' => 'required|integer',
            'seed_id'   => 'required|integer',
        ]);

        $credit = CreditsDeductable::where('client_id', $request->client_id)
            ->where('seed_id', $request->seed_id)
            ->first();

        if (!$credit) {
            return response()->json([
                'success' => false,
                'message' => '❌ No credit record found for this client and seed.'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'message' => '✅ Credit record found.',
            'data'    => $credit
        ]);
    }

public function committeaprova(Request $request): JsonResponse
{
    $validated = $request->validate([
        'client_id' => 'required|integer|exists:clients,id',
        'seed_id' => 'required|exists:inputsActivitiesCostsSeeds,id',
        'approved_amount' => 'required|numeric|min:0',
        'description' => 'required|string|max:500',
        'comments' => 'nullable|string|max:1000',
        'service_charges' => 'required|numeric|min:0',
        'mandatory_savings' => 'required|numeric|min:0',
        'total_deductions' => 'required|numeric|min:0',
        'total_loan_cost' => 'required|numeric|min:0',
        'cash_to_client' => 'required|numeric|min:0',
        'total_repayable' => 'required|numeric|min:0',
        'original_agent_proposal' => 'required|numeric|min:0',
        'client_original_request' => 'required|numeric|min:0'
    ]);

    try {
        // Add createdby before saving
        $validated['createdby'] = auth()->id(); // ✅ current authenticated user ID

        // 1️⃣ Save the committee approval
        $committeeApproval = CommitteeApproval::create($validated);

        // 2️⃣ Update the client's credit request status
        CreditRequest::where('client_id', $validated['client_id'])
                     ->update(['status' => 'approved']);

        // 3️⃣ Return success
        return response()->json([
            'message' => 'Committee approval submitted successfully!',
            'data' => $committeeApproval
        ], 201);

    } catch (\Exception $e) {
        \Log::error('Committee approval failed: '.$e->getMessage());

        return response()->json([
            'message' => 'Failed to submit committee approval',
            'error' => $e->getMessage()
        ], 500);
    }
}


public function loanaproved(){
 $records = CommitteeApproval::with([
        'client',
        'seed:id,seeds_name',
        'creditRequest' => function ($query) {
            $query->select(
                'id',
                'client_id',
                'request_date',
                'requested_amount',
                'purpose',
                'status',
                'disbursement_date',
                'interest_rate',
                'guarantee_type'
            );
        },
        'CreditDeductable' => function ($query) {
            $query->select(
                'id',
                'client_id',
                'request_date',
                'requested_amount',
                'purpose',
                'status',
                'disbursement_date',
                'interest_rate',
                'guarantee_type'
            );
        }
    ])->latest()->get();

    return response()->json($records);
}

}