<?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 request
        $request->validate([
            'front_id' => 'required|file|max:5120|mimetypes:image/jpeg,image/png,application/pdf',
            'back_id' => 'required|file|max:5120|mimetypes:image/jpeg,image/png,application/pdf',
            'proof_of_residence' => 'required|file|max:5120|mimetypes:image/jpeg,image/png,application/pdf',
        ]);

        $documents = [];
        $fields = ['front_id', 'back_id', 'proof_of_residence'];

        foreach ($fields as $field) {

            if ($request->hasFile($field)) {

                $file = $request->file($field);

                // Verify uploaded file security
                $this->verifyUploadedFile($file);

                // Store file
                $randomName = bin2hex(random_bytes(16)) . '.' . $file->extension();
                $path = $file->storeAs("kycs", $randomName, 'public');

                $documents[$field] = $path;
            }
        }

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

        // Create 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.'
        ]);
    }

    private function verifyUploadedFile($file)
    {
        $allowedMimes = [
            'image/jpeg',
            'image/png',
            'application/pdf'
        ];

        // Detect real MIME type
        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        $realMime = $finfo->file($file->getRealPath());

        if (!in_array($realMime, $allowedMimes)) {
            abort(422, 'Invalid file type detected.');
        }

        // Validate image structure
        if (str_starts_with($realMime, 'image/')) {
            if (@getimagesize($file->getRealPath()) === false) {
                abort(422, 'Invalid or corrupted image file.');
            }
        }

        // Validate PDF header
        if ($realMime === 'application/pdf') {
            $handle = fopen($file->getRealPath(), 'rb');
            $header = fread($handle, 4);
            fclose($handle);

            if ($header !== '%PDF') {
                abort(422, 'Invalid PDF file.');
            }
        }

        // Scan file for malicious content
        $content = file_get_contents($file->getRealPath());

        $dangerousPatterns = [
            '<?php',
            '<script',
            'eval(',
            'base64_decode',
            'system(',
            'shell_exec',
            'passthru('
        ];

        foreach ($dangerousPatterns as $pattern) {
            if (stripos($content, $pattern) !== false) {
                abort(422, 'Malicious content detected in file.');
            }
        }
    }

    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
        ]);
    }
}