<?php

namespace App\Http\Controllers\Admin\UCIC;


use App\Company;
use App\Http\Controllers\Controller;
use App\Logging\CloudWatchLoggerFactory;
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',
                'sessionKey' => 'UCIC_View|16-6-0',
                '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'));
        $ucicStatus = $this->request->get('ucic_status');
        $applicationId = $this->request->get('application_id');

        $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'
            ]);

        if (!empty($applicationId)) {
            $query->where('id', trim($applicationId));
        } else {
            $query->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);
                }
            });
        }

        if ($ucicStatus === 'ucic_generated' || $ucicStatus === 'generated') {
            $query->whereHas('ucicDetail', function($q) {
                $q->where('status', 'success');
            })->where(function($q) {
                $q->where(function($sq) {
                    $sq->whereNull('co_applicant_name')
                       ->orWhere('co_applicant_name', '');
                })->orWhereHas('coUcicDetail', function($sq) {
                    $sq->where('status', 'success');
                });
            });
        } elseif ($ucicStatus === 'create_ucic' || $ucicStatus === 'pending') {
            $query->where(function($q) {
                $q->whereDoesntHave('ucicDetail', function($sq) {
                    $sq->where('status', 'success');
                })->orWhere(function($sq) {
                    $sq->whereNotNull('co_applicant_name')
                       ->where('co_applicant_name', '!=', '')
                       ->whereDoesntHave('coUcicDetail', function($ssq) {
                           $ssq->where('status', 'success');
                       });
                });
            });
        }

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

        return view("admin.ucic.generate-ucic", compact('applications', 'fromDate', 'toDate', 'ucicStatus', 'applicationId'));
    }
    
    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`,
                    cae.type_of_customer,
                    '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.owner_name AS `Owner Name`,
                    m.address AS `Anchor Address`,
                    m.city AS `Anchor City`,
                    m.city AS `Anchor State`,
                    m.pincode AS `Anchor Pincode`
                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`,
                    cae.type_of_customer,
                    '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.owner_name AS `Owner Name`,
                    m.address AS `Anchor Address`,
                    m.city AS `Anchor City`,
                    m.city AS `Anchor State`,
                    m.pincode AS `Anchor Pincode`
                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;
                }

                $anchorEmail = wall_decrypt($applicant->{'Anchor Email'});

                $anchorEmailExploded = explode(',', $anchorEmail);


                $anchor_pan = wall_decrypt($applicant->{'Anchor PAN'});
                $anchor_constitution = $this->get_constitution($anchor_pan);

                $anchor_customer_type = 'other';
                if($anchor_constitution == 'private_limited'){
                    $anchor_customer_type = 'director';
                }else if($anchor_constitution == 'partnership'){
                    $anchor_customer_type == 'partner';
                }else if($anchor_constitution == 'proprietorship'){
                    $anchor_customer_type = 'proprietor';
                }

                $customer_pan = wall_decrypt($applicant->PAN);
                $customer_constitution = $this->get_constitution($customer_pan);

                if($applicant->type_of_customer == 1){
                    $customer_constitution = 'individual';
                }

                $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" => $customer_pan,
                        "customer_type" => $applicant->{'Customer Type'},
                        "customer_constitution" => $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 ? $applicant->State : $this->getStateFromAddress($applicant->Address),
                                "pin_code" => (string)$applicant->Pincode,
                                "country" => $applicant->Country
                            ]
                        ]
                    ],
                    "anchor_data" => [
                        "ref_id" => (string)$applicant->{'Anchor ID'},
                        "name" => $applicant->{'Anchor Name'},
                        "pan" => $anchor_pan,
                        "customer_type" => "anchor",
                        "customer_constitution" => $anchor_constitution,
                        "email" => $anchorEmailExploded[0] ?? '',
                        "mobile" => wall_decrypt($applicant->{'Anchor Mobile'}),
                        "address" => [
                            [
                                "type" => "residential",
                                "address" => $applicant->{'Anchor Address'},
                                "city" => $applicant->{'Anchor City'},
                                "state" => $applicant->{'Anchor State'} ? $applicant->{'Anchor State'} : $this->getStateFromAddress($applicant->{'Anchor Address'}),
                                "pin_code" => (string)$applicant->{'Anchor Pincode'},
                                "country" => "India"
                            ]
                        ]
                    ],
                    'anchor_person_data' => [
                        [
                            'name' => $applicant->{'Owner Name'},
                            'mobile' => wall_decrypt($applicant->{'Anchor Mobile'}),     
                            'customer_constitution' => 'individual',
                            'customer_type' => 'individual'
                        ]
                    ],
                    "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);
        }
    }
    

    public function get_constitution($pan){
        
        $fourthChar = strtoupper(substr($pan, 3, 1));

        $customer_constitution = 'others';

        if ($fourthChar == 'C') {
            $customer_constitution = 'private_limited';
        } elseif ($fourthChar == 'P') {
            $customer_constitution = 'proprietorship';
        } elseif ($fourthChar == 'H') {
            $customer_constitution = 'huf';
        } elseif ($fourthChar == 'T') {
            $customer_constitution = 'trust';
        } elseif ($fourthChar == 'F') {
            $customer_constitution = 'partnership';
        } elseif ($fourthChar == 'A') {
            $customer_constitution = 'society';
        }

        return $customer_constitution;
    }
 
    public function getStateFromAddress($address)
{
    $states = [
        'Andhra Pradesh',
        'Arunachal Pradesh',
        'Assam',
        'Bihar',
        'Chhattisgarh',
        'Goa',
        'Gujarat',
        'Haryana',
        'Himachal Pradesh',
        'Jharkhand',
        'Karnataka',
        'Kerala',
        'Madhya Pradesh',
        'Maharashtra',
        'Manipur',
        'Meghalaya',
        'Mizoram',
        'Nagaland',
        'Odisha',
        'Punjab',
        'Rajasthan',
        'Sikkim',
        'Tamil Nadu',
        'Telangana',
        'Tripura',
        'Uttar Pradesh',
        'Uttarakhand',
        'West Bengal'
    ];

    foreach ($states as $state) {
        if (stripos($address, $state) !== false) {
            return $state;
        }
    }

    return null;
}
}