<?php

namespace App\Http\Controllers\Api\User;

use App\Http\Controllers\Controller;
use App\Http\Controllers\User\KycController;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\KycRecord;
use App\Models\Notification;

class KycApiController extends Controller
{
    protected $kycController;

    public function __construct()
    {
        $this->kycController = new KycController();
    }

    /**
     * Get KYC status and data
     * @return JsonResponse
     */
    public function index(): JsonResponse
    {
        try {
            $user = auth()->user();
    
            // return unauthenticated if no user
            if (! $user) {
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Unauthenticated.'
                ], 401);
            }
    
            // Use the relation on the $user instance; optionally order results
            $kyc_records = $user->kycRecords()->latest()->get();
    
            return response()->json([
                'status' => 'success',
                'data'   => [
                    'kyc'  => $kyc_records,
                    'user' => $user
                ]
            ], 200);
    
        } catch (\Exception $e) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Failed to fetch KYC data',
                'error'   => $e->getMessage()
            ], 500);
        }
    }


    /**
     * Upload KYC documents
     * @param Request $request
     * @return JsonResponse
     */
public function upload(Request $request)
{
    try {
        // Use consistent field names: front_image, back_image, selfie_image
        $request->validate([
            'document_type' => 'nullable|string',
            'front_image'   => 'required',
            'back_image'    => 'nullable',
            'selfie_image'  => 'nullable',
        ]);
        
        $user = auth()->user();
        
        $path = 'kyc';
        $front = uploadImage($request->file('front_image'), $path);
        $back = null;
        if ($request->hasFile('back_image')) {
            $back = uploadImage($request->file('back_image'), $path);
        }
        $selfie = null;
        if ($request->hasFile('selfie_image')) {
            $selfie = uploadImage($request->file('selfie_image'), $path);
        }

        $photos = [
            'front' => $front,
            'back' => $back,
            'selfie' => $selfie,
        ];
        
        
        
        //save the kyc record
        $kyc = new KycRecord();
        $kyc->user_id = $user->id;
        $kyc->document_type = $request->document_type;
        $kyc->photos = json_encode($photos);
        $kyc->status = 'pending';
        $kyc->save();
        
        // return response()->json($kyc);

        
        sendKycMail($kyc);

        // $path = 'uploads/kyc';
        // $photos = [
        //     'front'  => null,
        //     'back'   => null,
        //     'selfie' => null,
        // ];

        // Helper to store file and return public path (ensure `php artisan storage:link`)
        // $storeFile = function ($file, $prefix) use ($path) {
        //     $name = time() . '_' . uniqid() . '_' . $prefix . '.' . $file->getClientOriginalExtension();
        //     $stored = $file->storeAs($path, $name, 'public'); // storage/app/public/...
        //     return 'storage/' . $stored; // public URL assumes php artisan storage:link
        // };

        // if ($request->hasFile('front_image')) {
        //     $photos['front'] = $storeFile($request->file('front_image'), 'front');
        // }

        // if ($request->hasFile('back_image')) {
        //     $photos['back'] = $storeFile($request->file('back_image'), 'back');
        // }

        // if ($request->hasFile('selfie_image')) {
        //     $photos['selfie'] = $storeFile($request->file('selfie_image'), 'selfie');
        // }

        // $kyc = new KycRecord();
        // $kyc->user_id = $user->id;
        // $kyc->document_type = $request->document_type;
        // $kyc->photos = json_encode($photos);
        // $kyc->status = 'pending';
        // $kyc->save();

        $notification = new Notification();
        $notification->user_id = $user->id;
        $notification->title = "KYC Verification";
        $notification->message = "KYC documents uploaded successfully!";
        $notification->status = 0;
        $notification->save();

        return response()->json([
            'status'  => 'success',
            'message' => 'KYC documents uploaded successfully',
            'data'    => ['kyc' => $kyc],
        ], 200);

    } catch (\Illuminate\Validation\ValidationException $ve) {
        return response()->json([
            'status'  => 'error',
            'message' => 'Validation failed',
            'errors'  => $ve->errors()
        ], 422);
    } catch (\Exception $e) {
        return response()->json([
            'status'  => 'error',
            'message' => 'Failed to upload KYC documents',
            'error'   => $e->getMessage(),
        ], 500);
    }
}

}