<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;

class KycController extends Controller
{


    public function verifyPan(Request $request)
{
    $request->validate([
        'id_number' => 'required|string',
    ]);

    $enteredPan = strtoupper(trim($request->id_number));

    // Early uniqueness check before API request
    $existingPanUser = \App\Models\User::where('pan_number', $enteredPan)
                        // ->where('id', '!=', auth()->id())
                        ->first();


    if ($existingPanUser) {
        return response()->json([
            'status'  => 'error',
            'message' => 'PAN number already registered with another user.',
        ], 422);
    }

    $baseUrl = env('SUREPASS_BASE_URL');
    $apiKey = env('SUREPASS_API_KEY');

    // Call SurePass API for PAN verification only if PAN is unique
    $response = Http::withHeaders([
        'Authorization' => "Bearer {$apiKey}",
        'Content-Type' => 'application/json',
    ])->post("{$baseUrl}/api/v1/pan/pan-comprehensive", [
        'id_number' => $enteredPan,
    ]);

    if ($response->failed()) {
        return response()->json([
            'status' => 'error',
            'message' => 'PAN verification failed',
            'error' => $response->json(),
        ], $response->status());
    }

    $jsonResponse = $response->json();
    $data = $jsonResponse['data'] ?? null;

    if (!$data) {
        return response()->json([
            'status' => 'error',
            'message' => 'No PAN data returned',
        ], 400);
    }

    $user = auth()->user();

    if (empty($user->aadhaar_masked) || empty($user->name) || empty($user->dob)) {
        return response()->json([
            'status' => 'error',
            'message' => 'Please complete Aadhaar verification first.',
        ], 422);
    }

    // Compare masked Aadhaar
    $storedAadhaar = preg_replace('/\s+/', '', strtoupper($user->aadhaar_masked));
    $apiAadhaar = preg_replace('/\s+/', '', strtoupper($data['masked_aadhaar'] ?? ''));

    if ($storedAadhaar !== $apiAadhaar) {
        return response()->json([
            'status' => 'error',
            'message' => 'PAN number does not match Aadhaar number, please enter a valid PAN number.',
        ], 422);
    }

    // Fuzzy match on full name stored from Aadhaar with PAN API name
    similar_text(
        strtolower(trim($user->name)),
        strtolower(trim($data['full_name'])),
        $nameSimilarity
    );

    // Flexible DOB match function
    $dobMatch = $this->dobMatch($user->dob, $data['dob'] ?? null);

    // Require masked Aadhaar + at least two of these: name similarity >= 80%, DOB match true
    $criteriaMet = 0;
    if ($nameSimilarity >= 80) {
        $criteriaMet++;
    }
    if ($dobMatch) {
        $criteriaMet++;
    }

    if ($criteriaMet < 1) { // At least one of name or DOB must match well
        return response()->json([
            'status' => 'error',
            'message' => 'Verification failed: name or DOB did not sufficiently match.',
            'name_similarity' => round($nameSimilarity, 2),
            'dob_match' => $dobMatch,
            'api_data' => $jsonResponse,
        ], 422);
    }

    // Save PAN number and optionally update user name
    $user->pan_number = $data['pan_number'];
    $user->save();

    return response()->json([
        'status' => 'success',
        'message' => 'PAN verified and saved successfully',
        'api_data' => $jsonResponse,
    ]);
}

/**
 * Flexible DOB match:
 * Accepts exact match or partial match (year and month equal)
 */
private function dobMatch($storedDob, $apiDob)
{
    if (empty($storedDob) || empty($apiDob)) {
        return false;
    }

    if ($storedDob === $apiDob) {
        return true;
    }

    try {
        $storedDate = new \DateTime($storedDob);
        $apiDate = new \DateTime($apiDob);
    } catch (\Exception $e) {
        return false;
    }

    return $storedDate->format('Y-m') === $apiDate->format('Y-m');
}




public function initDigiLocker(Request $request)
    {
        $baseUrl = env('SUREPASS_BASE_URL'); // e.g. https://sandbox.surepass.io
        $apiKey  = env('SUREPASS_API_KEY');



        $response = Http::withHeaders([
            'Authorization' => "Bearer {$apiKey}",
            'Content-Type'  => 'application/json',
        ])->post("{$baseUrl}/api/v1/digilocker/initialize", [
            'data' => [
                'signup_flow'  => true,
                'redirect_url' => 'https://google.com'
            ]
        ]);

        if ($response->failed()) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Failed to initialize DigiLocker',
                'error'   => $response->json()
            ], $response->status());
        }

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



    public function downloadAadhaar($clientId)
 {
    $baseUrl = env('SUREPASS_BASE_URL');
    $apiKey  = env('SUREPASS_API_KEY');

    $response = Http::withHeaders([
        'Authorization' => "Bearer {$apiKey}",
    ])->get("{$baseUrl}/api/v1/digilocker/download-aadhaar/{$clientId}");

    if ($response->failed()) {
        return response()->json([
            'status'  => 'error',
            'message' => 'Failed to download Aadhaar data',
            'error'   => $response->json()
        ], $response->status());
    }

    $data = $response->json()['data'] ?? [];
    $aadhaarXml = $data['aadhaar_xml_data'] ?? [];

    $user = auth()->user();
    $user->name = $aadhaarXml['full_name'] ?? null;
    $user->dob = $aadhaarXml['dob'] ?? null;
    $user->gender = $aadhaarXml['gender'] ?? null;
    $user->address = $aadhaarXml['full_address'] ?? null;
    $user->aadhaar_masked = $aadhaarXml['masked_aadhaar'] ?? null;
    $user->save();

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

}
