<?php

namespace App\Http\Controllers;

use App\Http\Requests\LiveAnalysisUploadRequest;
use App\Services\LiveAnalysisService;
use Illuminate\Http\Request;

class LiveAnalysisController extends Controller
{
    public function __construct(
        protected LiveAnalysisService $liveAnalysisService
    ) {}

    public function index(Request $request)
    {
        $this->authorize('analysisViewAny', $request->attributes->get('current_organization'));

        return view('pages.live-analysis', [
            'page_title' => 'Phân Tích Phiên Live',
        ]);
    }

    public function upload(LiveAnalysisUploadRequest $request)
    {
        $this->authorize('analysisUpload', $request->attributes->get('current_organization'));

        try {
            set_time_limit(0);
            ini_set('memory_limit', '1G');
            gc_enable();

            $path = $this->liveAnalysisService->storeUpload($request->file('file'));
            $result = $this->liveAnalysisService->processFile($path);

            $this->liveAnalysisService->deleteUpload($path);

            $result['success'] = true;
            session(['live_analysis_result' => $result]);

            return response()->json($result);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Lỗi xử lý file: ' . $e->getMessage(),
            ], 422);
        }
    }

    /**
     * Lấy dữ liệu phân tích phiên live đã lưu trong session
     */
    public function sessionData(Request $request)
    {
        $this->authorize('analysisViewAny', $request->attributes->get('current_organization'));

        return response()->json([
            'success' => true,
            'data' => session('live_analysis_result'),
        ]);
    }

    /**
     * Xoá dữ liệu phân tích phiên live khỏi session
     */
    public function clearSession(Request $request)
    {
        $this->authorize('analysisUpload', $request->attributes->get('current_organization'));

        session()->forget('live_analysis_result');

        return response()->json([
            'success' => true,
            'message' => 'Đã xoá dữ liệu phân tích.',
        ]);
    }
}