<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Notification;
use App\Mail\KycEmail;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;

class KycController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        return view('user.kyc', [
            'kycStatus' => $user->getKycStatus()
        ]);
    }

    public function uploadDocuments(Request $request)
    {
        $user = Auth::user();
        
        // Validate the request
        $request->validate([
            'front_id' => 'required|file|mimes:jpg,jpeg,png,pdf|max:5120',
            'back_id' => 'required|file|mimes:jpg,jpeg,png,pdf|max:5120',
            'proof_of_residence' => 'required|file|mimes:jpg,jpeg,png,pdf|max:5120',
        ]);

        // Store files
        $documents = [];
        $fields = ['front_id', 'back_id', 'proof_of_residence'];
        foreach ($fields as $field) {
            if ($request->hasFile($field)) {
                $file = $request->file($field);
                $path = $file->store("kycs", 'public');
                $documents[$field] = $path;
            }
        }

        // Update user's KYC documents
        $user->updateKycDocuments($documents);

        // Create KYC document upload notification
        Notification::create([
            'user_id' => $user->id,
            'type' => 'kyc_upload',
            'title' => 'KYC Documents Uploaded',
            'message' => 'Your KYC documents have been submitted for verification.',
            'is_read' => false,
            'extra_data' => json_encode([
                'documents_uploaded' => array_keys($documents),
                'upload_timestamp' => now()->toDateTimeString()
            ])
        ]);

        // Send email notification
        Mail::to($user->email)->queue(new KycEmail(
            $user,
            'submission',
            $documents
        ));

        return response()->json([
            'status' => 'success',
            'message' => 'KYC documents uploaded successfully. Verification is pending.'
        ]);
    }

    public function getDocumentStatus()
    {
        $user = Auth::user();
        return response()->json([
            'status' => $user->getKycStatus(),
            'front_id' => $user->front_id,
            'back_id' => $user->back_id,
            'proof_of_residence' => $user->proof_of_residence
        ]);
    }
}