<?php

namespace App\Http\Controllers;

use App\Models\SellerDocument;
use App\Models\DocumentAccessLog;
use App\Models\DocumentAccessRule;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SellerDocumentController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $documents = auth()->user()->documents()
            ->orderByDesc('created_at')
            ->paginate(15);

        return view('seller-documents.index', compact('documents'));
    }

    public function create()
    {
        if (auth()->user()->role !== 'seller') {
            abort(403);
        }

        return view('seller-documents.create');
    }

    public function store(Request $request)
    {
        if (auth()->user()->role !== 'seller') {
            abort(403);
        }

        $validated = $request->validate([
            'type' => 'required|in:kyc_id,kyc_address,business_license,tax_id,bank_account',
            'file' => 'required|file|max:10240', // 10MB max
        ]);

        DB::beginTransaction();
        try {
            $file = $request->file('file');
            $path = "seller-documents/" . auth()->id() . "/" . time() . "_" . $file->getClientOriginalName();
            
            // Stockage sécurisé (S3)
            $storagePath = Storage::disk('s3')->putFile($path, $file);
            
            // Créer document
            $document = SellerDocument::create([
                'user_id' => auth()->id(),
                'type' => $validated['type'],
                'file_path' => $storagePath,
                'file_url' => Storage::disk('s3')->url($storagePath),
                'file_hash' => hash_file('sha256', $file),
                'mime_type' => $file->getMimeType(),
                'file_size' => $file->getSize(),
                'status' => 'pending',
            ]);

            // Déclencher scan virus (async job)
            dispatch(new \App\Jobs\ScanDocumentForVirus($document));

            DB::commit();
            return redirect()->route('seller-documents.index')->with('success', 'Document uploadé. Scan antivirus en cours.');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error("Erreur upload document: " . $e->getMessage());
            return redirect()->back()->with('error', 'Erreur lors de l\'upload.');
        }
    }

    public function show(SellerDocument $document)
    {
        $user = auth()->user();

        // Vérifier accès
        if (!$this->canAccess($document, $user, 'view')) {
            abort(403);
        }

        // Logger accès
        DocumentAccessLog::create([
            'document_id' => $document->id,
            'accessed_by' => $user->id,
            'action' => 'viewed',
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ]);

        $document->increment('view_count');

        return view('seller-documents.show', compact('document'));
    }

    public function download(SellerDocument $document)
    {
        $user = auth()->user();

        // Vérifier accès
        if (!$this->canAccess($document, $user, 'download')) {
            abort(403);
        }

        // Logger accès
        DocumentAccessLog::create([
            'document_id' => $document->id,
            'accessed_by' => $user->id,
            'action' => 'downloaded',
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ]);

        return Storage::disk('s3')->download($document->file_path);
    }

    public function verify(Request $request, SellerDocument $document)
    {
        if (!auth()->user()->hasRole('admin,verifier')) {
            abort(403);
        }

        $validated = $request->validate([
            'status' => 'required|in:verified,rejected',
            'rejection_reason' => 'nullable|string|min:10',
        ]);

        $document->update([
            'status' => $validated['status'],
            'verified_by' => auth()->id(),
            'verified_at' => now(),
            'rejection_reason' => $validated['rejection_reason'] ?? null,
            'expires_at' => $validated['status'] === 'verified' ? now()->addYears(1) : null,
        ]);

        Log::info("Document #{$document->id} {$validated['status']} par " . auth()->user()->name);

        return redirect()->back()->with('success', 'Document mis à jour.');
    }

    public function accessLogs(SellerDocument $document)
    {
        if ($document->user_id !== auth()->id() && !auth()->user()->hasRole('admin')) {
            abort(403);
        }

        $logs = $document->accessLogs()->orderByDesc('created_at')->paginate(20);

        return view('seller-documents.access-logs', compact('document', 'logs'));
    }

    private function canAccess(SellerDocument $document, User $user, $action)
    {
        // Owner toujours accès
        if ($document->user_id === $user->id) {
            return true;
        }

        // Vérifier règles d'accès
        $rule = DocumentAccessRule::where('document_id', $document->id)
            ->where(function ($q) use ($user) {
                $q->where('user_id', $user->id)
                  ->orWhere('role', $user->role);
            })
            ->first();

        if (!$rule) {
            return false;
        }

        if ($action === 'view') {
            return $rule->can_view;
        } elseif ($action === 'download') {
            return $rule->can_download;
        }

        return false;
    }
}
