<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\ImmigoProQuotationQuestion;
use App\Models\ImmigoProQuotationAnswer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class ImmigoProQuotationAnswerController extends Controller
{
    /**
     * Get all active questions for client form
     */
    public function getActiveQuestions()
    {
        try {
            $questions = ImmigoProQuotationQuestion::where('is_active', true)
                ->orderBy('order')
                ->get(['id', 'question', 'type', 'options', 'required', 'placeholder', 'help_text']);

            return response()->json([
                'success' => true,
                'data' => $questions
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch questions',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get user's answers
     */
    public function getUserAnswers(Request $request)
    {
        try {
            $userId = Auth::id();
            
            $answers = ImmigoProQuotationAnswer::where('user_id', $userId)
                ->with('question:id,question,type,options')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $answers
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch answers',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Upload file for quotation answer
     */
    public function uploadFile(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'file' => 'required|file|max:10240', // 10MB max
                'question_id' => 'required|exists:immigopro_quotation_questions,id',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $userId = Auth::id();
            $file = $request->file('file');
            $questionId = $request->question_id;

            // Create directory path
            $directory = "immigopro/quotations/user_{$userId}";
            
            // Store file with original name
            $filename = time() . '_' . $file->getClientOriginalName();
            $path = $file->storeAs($directory, $filename, 'public');

            return response()->json([
                'success' => true,
                'file_path' => $path,
                'file_name' => $file->getClientOriginalName(),
                'file_url' => Storage::url($path)
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to upload file',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Submit/Update quotation answers
     */
    public function submitAnswers(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'answers' => 'required|array',
                'answers.*.question_id' => 'required|exists:immigopro_quotation_questions,id',
                'answers.*.answer' => 'nullable',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $userId = Auth::id();
            $answers = $request->answers;

            foreach ($answers as $answerData) {
                ImmigoProQuotationAnswer::updateOrCreate(
                    [
                        'user_id' => $userId,
                        'question_id' => $answerData['question_id']
                    ],
                    [
                        'answer' => $answerData['answer']
                    ]
                );
            }

            return response()->json([
                'success' => true,
                'message' => 'Quotation submitted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to submit quotation',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
