<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Response;
use App\Mail\ResponseMail;
use Barryvdh\DomPDF\Facade\Pdf;
use Mail;

class QuizController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $response = Response::where('email', auth()->user()->email)->first();
        if (!$response) {
            $response = new Response([
                'team_status' => 'Seul',
                'team_size' => null,
                'members' => null,
                'firstname' => null,
                'lastname' => null,
                'sex' => null,
                'birthdate' => null,
                'address' => null,
                'city' => null,
                'state' => null,
                'phone_number' => null,
                'email' => auth()->user()->email,
                'professional_status' => null,
                'educational_level' => null,
                'project_type' => null,
                'idea_bearer' => null,
                'innovative_project_or_labeled_startup' => null,
                'project_name' => null,
                'project_description' => null,
                'type_solution' => null,
                'why_designed_agritech' => null,
                'capable_startup' => null,
                'competence_startup' => null,
                'understand_challenges' => null,
                'financial_management' => null,
                'develop_prototype' => null,
                'status' => 'draft',
            ]);
        }

        $wilayas = config('wilayas');

        return view('quiz.index', compact('response', 'wilayas'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $existingResponse = Response::where('email', $request->email)->where('status', 'submitted')->first();
        if ($existingResponse) {
            return redirect()->back()->with('error', 'Vous avez déjà soumis le quiz.');
        }

        if ($request->input('auto_save') == '1') {
            $request->merge([
                'status' => 'draft'
            ]);
            $request->validate([
                'team_status' => 'nullable|in:Seul,En équipe',
                'team_size' => 'nullable|integer|min:1',
                'members' => 'nullable|array',
                'members.*' => 'nullable|max:255',
                'firstname' => 'nullable|string|max:255',
                'lastname' => 'nullable|string|max:255',
                'sex' => 'nullable|string|max:255',
                'birthdate' => 'nullable|date|before:today',
                'address' => 'nullable|string|max:255',
                'city' => 'nullable|string|max:255',
                'state' => 'nullable|in:' . implode(',', array_keys(config('wilayas'))).'|string|max:255',
                'phone_number' => 'nullable|string|min:10|max:15|regex:/^\+?[0-9\s\-]+$/',
                'email' => 'required|email',
                'professional_status' => 'nullable|string|max:255',
                'educational_level' => 'nullable|string|max:255',
                'project_type' => 'nullable|string|max:255',
                'idea_bearer' => 'nullable|string|max:255',
                'innovative_project_or_labeled_startup' => 'nullable|string|max:255',
                'project_name' => 'nullable|string|max:255',
                'project_description' => 'nullable|string|max:1000',
                'type_solution' => 'nullable|string|max:255',
                'why_designed_agritech' => 'nullable|string|max:1000',
                'capable_startup' => 'nullable|numeric|min:1|max:10',
                'competence_startup' => 'nullable|numeric|min:1|max:10',
                'understand_challenges' => 'nullable|numeric|min:1|max:10',
                'financial_management' => 'nullable|numeric|min:1|max:10',
                'develop_prototype' => 'nullable|numeric|min:1|max:10',
            ]);

            $response = Response::updateOrCreate(
                ['email' => $request->email],
                $request->all()
            );
        } else {
            $request->merge([
                'status' => 'submitted'
            ]);
            $request->validate([
                'team_status' => 'required|in:Seul,En équipe',
                'team_size' => 'required_if:team_status,En équipe|integer|min:1',
                'members' => 'required_if:team_status,En équipe|array',
                'members.*' => 'required_if:team_status,En équipe|max:255',
                'firstname' => 'required|string|max:255',
                'lastname' => 'required|string|max:255',
                'sex' => 'required|string|max:255',
                'birthdate' => 'required|date|before:today',
                'address' => 'required|string|max:255',
                'city' => 'required|string|max:255',
                'state' => 'required|in:' . implode(',', array_keys(config('wilayas'))).'|string|max:255',
                'phone_number' => 'required|string|min:10|max:15|regex:/^\+?[0-9\s\-]+$/',
                'email' => 'required|email',
                'professional_status' => 'required|string|max:255',
                'educational_level' => 'required|string|max:255',
                'project_type' => 'required|string|max:255',
                'idea_bearer' => 'required_if:project_type,Un porteur d’idée|string|max:255',
                'innovative_project_or_labeled_startup' => 'required_if:project_type,Projet innovant ou startup labellisés|string|max:255',
                'project_name' => 'required|string|max:255',
                'project_description' => 'required|string|max:1000',
                'type_solution' => 'required|string|max:255',
                'why_designed_agritech' => 'required|string|max:1000',
                'capable_startup' => 'required|numeric|min:1|max:10',
                'competence_startup' => 'required|numeric|min:1|max:10',
                'understand_challenges' => 'required|numeric|min:1|max:10',
                'financial_management' => 'required|numeric|min:1|max:10',
                'develop_prototype' => 'required|numeric|min:1|max:10',
                'toc' => 'accepted',
                'data_consent' => 'accepted',
            ]);

            $response = Response::updateOrCreate(
                ['email' => $request->email],
                $request->all()
            );

            // Générer le PDF
            $pdf = PDF::loadView('pdf.response', compact('response'));

            // Stocker temporairement le PDF
            $pdfPath = storage_path('app/public/response_' . $response->id . '.pdf');
            $pdf->save($pdfPath);

            // Envoyer l'email avec le PDF en pièce jointe
            Mail::to($response->email)->send(new ResponseMail($response, $pdfPath));
        }

        return redirect()->route('quiz.index')->with('success', $request->input('auto_save') == '1' ? 'Quiz sauvegarder !' : 'Quiz soumis !');
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
