<?php

namespace App\Http\Controllers\Pages;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\TrialBooking;
use App\Models\SiteSetting;
use App\Notifications\TrialBookingSubmitted;
use Illuminate\Support\Facades\Notification;

class TrialBookingController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:50'],
            'phone' => ['required', 'string', 'max:20'],
            'goal' => ['required', 'string', 'max:200'],
            'availability' => ['required', 'array', 'min:1'],
            'availability.*' => ['string', 'max:20'],
            'level' => ['nullable', 'string', 'max:20'],
            'has_experience' => ['nullable', 'in:yes,no'],
            'notes' => ['nullable', 'string', 'max:500'],
        ]);

        $settings = SiteSetting::current();
        $duplicateWindowDays = (int) ($settings->duplicate_window_days ?? 0);

        if ($duplicateWindowDays > 0) {
            $cutoff = now()->subDays($duplicateWindowDays);
            $exists = TrialBooking::query()
                ->where('phone', $data['phone'])
                ->where('created_at', '>=', $cutoff)
                ->exists();

            if ($exists) {
                return back()
                    ->withInput()
                    ->withErrors([
                        'phone' => '此手機近期已有預約紀錄，請稍後再試或與我們聯絡。',
                    ]);
            }
        }

        $booking = TrialBooking::query()->create([
            'name' => $data['name'],
            'phone' => $data['phone'],
            'goal' => $data['goal'],
            'availability' => $data['availability'],
            'level' => $data['level'] ?? null,
            'has_experience' => $data['has_experience'] ?? null,
            'notes' => $data['notes'] ?? null,
            'ip' => $request->ip(),
            'user_agent' => substr((string) $request->userAgent(), 0, 255),
        ]);

        $emails = SiteSetting::parseEmails((string) ($settings->admin_emails ?? ''));
        if (! empty($emails)) {
            Notification::route('mail', $emails)
                ->notify(new TrialBookingSubmitted($booking));
        }

        return back()->with('booking_success', true);
    }
}
