<?php

namespace App\Http\Controllers\Admin\UCIC;


use App\Company;
use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Http\Request;
use App\UCIC\UCICService;
use Illuminate\Support\Facades\Log;

class UCICController extends Controller{

    private $request;

    public function __construct(Request $request){

        $this->request = $request;
    }

    public static function registry(){
        return [
            [
                'name'    => 'UCIC',
                'summary' => 'Manage UCIC dashboard configurations and details.',
                'url'     => '/admin/ucic',
            ],
        ];
    }

    public function index(){
        $fromDate = $this->request->get('from_date', \Carbon\Carbon::now()->subWeek()->format('Y-m-d'));
        $toDate = $this->request->get('to_date', \Carbon\Carbon::now()->format('Y-m-d'));

        $query = \App\ConsumerApplication::select('id', 'name', 'co_applicant_name', 'merchant_id')
            ->with([
                'merchant:id,merchant_name', 
                'ucicDetail:id,application_id,status,ucic_id',
                'coUcicDetail:id,application_id,status,ucic_id'
            ])
            ->whereHas('logs', function($q) use ($fromDate, $toDate) {
                $q->where('status', 'disbursed');
                if ($fromDate) {
                    $q->whereDate('created_at', '>=', $fromDate);
                }
                if ($toDate) {
                    $q->whereDate('created_at', '<=', $toDate);
                }
            });

        $applications = $query->orderBy('id', 'desc')->paginate(20);

        return view("admin.ucic.generate-ucic", compact('applications', 'fromDate', 'toDate'));
    }
    
    public function generateUCIC(){
        $ucicService = new UCICService();

        try {
            $applicationId = $this->request->get('application_id');
            
            $sql = "
                SELECT
                    1 AS `applicant_type`,
                    ca.id AS `Reference ID`,
                    ca.pan_card AS `PAN`,
                    CASE
                        WHEN cae.type_of_entity = 'Housing Society' THEN 'society'
                        WHEN cae.type_of_entity = 'Partnership Firm/LLP' THEN 'partnership'
                        WHEN cae.type_of_entity = 'Proprietorships' THEN 'proprietorship'
                        WHEN cae.type_of_entity = 'Individual' THEN 'individual'
                        WHEN cae.type_of_entity IS NULL OR TRIM(cae.type_of_entity) = '' THEN 'others'
                        ELSE 'others'
                    END AS `Customer Constitution`,
                    'borrower' AS `Customer Type`,
                    company_name,
                    cae.gst_number,
                    ca.name AS `Name`,
                    ca.mobile_number AS `Mobile`,
                    ca.email AS `Email`,
                    if(permanent_address_line_1 is null,'communicationAddress','residential') AS `Address Type`,
                    ifnull(permanent_address_line_1, current_address_line_1) AS `Address`,
                    if(permanent_address_line_1 is null,current_address_state,permanent_address_state) AS `State`,
                    if(permanent_address_line_1 is null,current_address_city,permanent_address_city) AS `City`,
                    if(permanent_address_line_1 is null,current_address_pincode,permanent_address_pincode) AS `Pincode`,
                    'India' AS `Country`,
                    ca.id AS `Application ID`,
                    ca.id AS `Loan ID`,
                    'Term Loan' AS `Product Name`,
                    'RETAIL' AS `Segment Type`,
                    ca.merchant_id AS `Anchor ID`,
                    m.merchant_name AS `Anchor Name`,
                    m.pan_card AS `Anchor PAN`,
                    m.email AS `Anchor Email`,
                    m.contact_number AS `Anchor Mobile`,
                    m.address AS `Anchor Address`
                FROM consumer_application ca
                LEFT JOIN consumer_application_element cae
                    ON cae.application_id = ca.id
                LEFT JOIN merchant m
                    ON m.id = ca.merchant_id
                WHERE ca.id = ?

                UNION ALL

                SELECT
                    2 AS `applicant_type`,
                    ca.id AS `Reference ID`,
                    ca.co_applicant_pan_card AS `PAN`,
                    CASE
                        WHEN cae.type_of_entity = 'Housing Society' THEN 'society'
                        WHEN cae.type_of_entity = 'Partnership Firm/LLP' THEN 'partnership'
                        WHEN cae.type_of_entity = 'Proprietorships' THEN 'proprietorship'
                        WHEN cae.type_of_entity = 'Individual' THEN 'individual'
                        WHEN cae.type_of_entity IS NULL OR TRIM(cae.type_of_entity) = '' THEN 'others'
                        ELSE 'others'
                    END AS `Customer Constitution`,
                    'borrower' AS `Customer Type`,
                    company_name,
                    cae.gst_number,
                    ca.co_applicant_name AS `Name`,
                    ca.co_applicant_mobile_number AS `Mobile`,
                    ca.co_applicant_email AS `Email`,
                    if(co_applicant_address_line_1 is null, if(permanent_address_line_1 is null,'communicationAddress','residential'), 'residential') AS `Address Type`,
                    ifnull(co_applicant_address_line_1, ifnull(permanent_address_line_1, current_address_line_1)) AS `Address`,
                    if(co_applicant_address_line_1 is null, if(permanent_address_line_1 is null,current_address_state,permanent_address_state), co_applicant_address_state) AS `State`,
                    if(co_applicant_address_line_1 is null, if(permanent_address_line_1 is null,current_address_city,permanent_address_city), co_applicant_address_city) AS `City`,
                    if(co_applicant_address_line_1 is null, if(permanent_address_line_1 is null,current_address_pincode,permanent_address_pincode), co_applicant_address_pincode) AS `Pincode`,
                    'India' AS `Country`,
                    ca.id AS `Application ID`,
                    ca.id AS `Loan ID`,
                    'Term Loan' AS `Product Name`,
                    'RETAIL' AS `Segment Type`,
                    ca.merchant_id AS `Anchor ID`,
                    m.merchant_name AS `Anchor Name`,
                    m.pan_card AS `Anchor PAN`,
                    m.email AS `Anchor Email`,
                    m.contact_number AS `Anchor Mobile`,
                    m.address AS `Anchor Address`
                FROM consumer_application ca
                LEFT JOIN consumer_application_element cae
                    ON cae.application_id = ca.id
                LEFT JOIN merchant m
                    ON m.id = ca.merchant_id
                WHERE ca.id = ? AND ca.co_applicant_name IS NOT NULL AND TRIM(ca.co_applicant_name) != ''
            ";

            $rows = \Illuminate\Support\Facades\DB::select($sql, [$applicationId, $applicationId]);

            if (empty($rows)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Application not found or invalid'
                ], 404);
            }

            $ucicIds = [];
            $apiResponses = [];
            $hasError = false;
            $errorResponse = null;

            foreach ($rows as $index => $applicant) {
                $applicantType = $applicant->applicant_type;

                // Check if this specific applicant_type has already been successfully onboarded
                $existing = \App\UcicDetail::where('application_id', $applicationId)
                    ->where('applicant_type', $applicantType)
                    ->where('status', 'success')
                    ->first();

                if ($existing) {
                    if (!empty($existing->ucic_id)) {
                        $ucicIds[] = $existing->ucic_id;
                    }
                    $apiResponses[] = [
                        'customer_type' => $applicant->{'Customer Type'},
                        'name' => $applicant->Name,
                        'applicant_type' => $applicantType,
                        'status' => 'success',
                        'response' => json_decode($existing->api_response, true) ?: $existing->api_response
                    ];
                    continue;
                }

                $params = [
                    "product_name" => $applicant->{'Product Name'},
                    "anchor_id" => (string)$applicant->{'Anchor ID'},
                    "business_id" => (string)$applicant->{'Reference ID'},
                    "business_data" => [
                        "ref_id" => (string)$applicant->{'Reference ID'},
                        "name" => $applicant->Name,
                        "pan" => wall_decrypt($applicant->PAN),
                        "customer_type" => $applicant->{'Customer Type'},
                        "customer_constitution" => $applicant->{'Customer Constitution'},
                        "email" => wall_decrypt($applicant->Email),
                        "mobile" => wall_decrypt($applicant->Mobile),
                        "address" => [
                            [
                                "type" => $applicant->{'Address Type'},
                                "address" => $applicant->Address,
                                "city" => $applicant->City,
                                "state" => $applicant->State,
                                "pin_code" => (string)$applicant->Pincode,
                                "country" => $applicant->Country
                            ]
                        ]
                    ],
                    "anchor_data" => [
                        "ref_id" => (string)$applicant->{'Anchor ID'},
                        "name" => $applicant->{'Anchor Name'},
                        "pan" => wall_decrypt($applicant->{'Anchor PAN'}),
                        "customer_type" => "anchor",
                        "customer_constitution" => "others",
                        "email" => wall_decrypt($applicant->{'Anchor Email'}),
                        "mobile" => wall_decrypt($applicant->{'Anchor Mobile'}),
                        "address" => [
                            [
                                "type" => "residential",
                                "address" => $applicant->{'Anchor Address'},
                                "country" => "India"
                            ]
                        ]
                    ],
                    "loan_data" => [
                        [
                            "application_id" => (string)$applicant->{'Application ID'},
                            "loan_id" => (string)$applicant->{'Loan ID'},
                            "segment_id" => $applicant->{'Segment Type'}
                        ]
                    ]
                ];

                if (in_array($params['business_data']['customer_constitution'], ['proprietorship'])) {
                    $company = Company::where('id', $applicant->{'company_name'})->first(['id', 'company']);
                    $company_name = $company->company ?? $applicant->company_name;

                    $params['business_data'] = array_merge($params['business_data'], [
                        "company_name" => $company_name,
                        "company_gstin" => $applicant->gst_number ?? '',
                        'customer_constitution' => 'individual'
                    ]);
                }

                // Push the payload to UCIC
                $response = $ucicService->pushOnboarding($params);

                $responseData = $response->json();
                $apiResponses[] = [
                    'customer_type' => $applicant->{'Customer Type'},
                    'name' => $applicant->Name,
                    'applicant_type' => $applicantType,
                    'status' => $response->successful() ? 'success' : 'failed',
                    'response' => $responseData ?: $response->body()
                ];

                $ucicDetail = \App\UcicDetail::firstOrNew([
                    'application_id' => $applicationId,
                    'applicant_type' => $applicantType
                ]);
                $ucicDetail->api_response = json_encode($responseData ?: $response->body());
                $ucicDetail->created_by = Auth::user()->id ?? 107;

                if ($response->successful()) {
                    $ucicDetail->status = 'success';
                    if (isset($responseData['businessData']['ucic'])) {
                        $ucicDetail->ucic_id = $responseData['businessData']['ucic'];
                        $ucicIds[] = $responseData['businessData']['ucic'];
                    }
                } else {
                    $ucicDetail->status = 'failed';
                    $hasError = true;
                    $errorResponse = $response;
                }
                $ucicDetail->save();
            }

            // Handle non-2xx responses from the external API
            if ($hasError) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'UCIC API request failed',
                    'error' => $errorResponse->json() ?: $errorResponse->body(),
                    'details' => $apiResponses
                ], $errorResponse->status());
            }

            // Return successful response
            return response()->json([
                'status' => 'success',
                'message' => 'Successfully pushed onboarding data to UCIC',
                'data' => [
                    'businessData' => [
                        'ucic' => implode(' / ', $ucicIds)
                    ],
                    'responses' => $apiResponses
                ],
            ], 200);

        } catch (\Exception $e) {
            Log::error('UCIC generateUCIC Exception: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString(),
                'request_data' => $this->request->all(),
            ]);

            return response()->json([
                'status' => 'error',
                'message' => 'An internal error occurred while processing the request',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
    
}