<?php

namespace App\Http\Controllers\Page;

use App\Http\Controllers\Controller;
use App\Models\Agency\Agency;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class AgencyRegistrationController extends Controller
{
    public function showRegisterForm()
    {
        return view('customer.agency.register');
    }

    public function register(Request $request)
    {
        $validated = $request->validate([
            // Agency Info
            'agency_name' => 'required|string|max:255|unique:agencies,name',
            'description' => 'nullable|string|max:1000',
            'business_type' => 'required|string|in:travel_agency,tour_operator,both',

            // Contact Info
            'contact_person' => 'required|string|max:255',
            'contact_phone' => 'required|string|max:15',
            'contact_email' => 'required|email|max:255|unique:agencies,contact_email',
            'contact_address' => 'required|string|max:500',
            'website_url' => 'nullable|url|max:255',

            // Legal Info
            'tax_number' => 'required|string|max:20',
            'tax_certificate_file' => 'required|file|mimes:pdf,jpg,jpeg,png|max:5120',
            'tursab_certificate_file' => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120',
            'tursab_activity_certificate_file' => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120',
            'tursab_registry_certificate_file' => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120',

            // Social Media
            'facebook_url' => 'nullable|url|max:255',
            'twitter_url' => 'nullable|url|max:255',
            'instagram_url' => 'nullable|url|max:255',
            'youtube_url' => 'nullable|url|max:255',

            // Owner Info
            'owner_first_name' => 'required|string|max:255',
            'owner_last_name' => 'required|string|max:255',
            'owner_email' => 'required|email|max:255|unique:users,email',
            'owner_phone' => 'required|string|max:15',
            'owner_national_id' => 'required|string|size:11',
            'owner_password' => 'required|string|min:8|confirmed',

            // Terms
            'terms' => 'required|accepted',
            'kvkk' => 'required|accepted',
        ], [
            'agency_name.unique' => 'Bu acente adı zaten kullanımda.',
            'contact_email.unique' => 'Bu e-posta adresi zaten kullanımda.',
            'owner_email.unique' => 'Bu e-posta adresi zaten kullanımda.',
            'tax_certificate_file.required' => 'Vergi levhası zorunludur.',
            'terms.accepted' => 'Kullanım koşullarını kabul etmelisiniz.',
            'kvkk.accepted' => 'KVKK metnini kabul etmelisiniz.',
        ]);

        DB::beginTransaction();

        try {
            // File uploads
            $taxCertPath = $request->file('tax_certificate_file')->store('agencies/documents', 'public');
            $tursabCertPath = $request->hasFile('tursab_certificate_file')
                ? $request->file('tursab_certificate_file')->store('agencies/documents', 'public')
                : null;
            $tursabActivityPath = $request->hasFile('tursab_activity_certificate_file')
                ? $request->file('tursab_activity_certificate_file')->store('agencies/documents', 'public')
                : null;
            $tursabRegistryPath = $request->hasFile('tursab_registry_certificate_file')
                ? $request->file('tursab_registry_certificate_file')->store('agencies/documents', 'public')
                : null;

            // Create Agency
            $agency = Agency::create([
                'name' => $validated['agency_name'],
                'slug' => Str::slug($validated['agency_name']),
                'description' => $validated['description'],
                'business_type' => $validated['business_type'],
                'contact_person' => $validated['contact_person'],
                'contact_phone' => $validated['contact_phone'],
                'contact_email' => $validated['contact_email'],
                'contact_address' => $validated['contact_address'],
                'website_url' => $validated['website_url'],
                'tax_number' => $validated['tax_number'],
                'tax_certificate_file' => $taxCertPath,
                'tursab_certificate_file' => $tursabCertPath,
                'tursab_activity_certificate_file' => $tursabActivityPath,
                'tursab_registry_certificate_file' => $tursabRegistryPath,
                'facebook_url' => $validated['facebook_url'],
                'twitter_url' => $validated['twitter_url'],
                'instagram_url' => $validated['instagram_url'],
                'youtube_url' => $validated['youtube_url'],
                'is_active' => true,
                'is_approved' => false,
            ]);

            // Create Owner User
            $user = User::create([
                'first_name' => $validated['owner_first_name'],
                'last_name' => $validated['owner_last_name'],
                'email' => $validated['owner_email'],
                'phone' => $validated['owner_phone'],
                'national_id' => $validated['owner_national_id'],
                'password' => Hash::make($validated['owner_password']),
                'agency_id' => $agency->id,
                'is_agency_owner' => true,
                'is_active' => true,
                'is_verified' => false,
            ]);

            $user->assignRole('agency-owner');

            DB::commit();

            return redirect()->route('agency.register')
                ->with('success', 'Başvurunuz alındı! Yönetici onayından sonra sisteme giriş yapabileceksiniz. Onay süreci e-posta ile bildirilecektir.');

        } catch (\Exception $e) {
            DB::rollBack();

            // Clean up uploaded files
            if (isset($taxCertPath)) Storage::disk('public')->delete($taxCertPath);
            if (isset($tursabCertPath)) Storage::disk('public')->delete($tursabCertPath);
            if (isset($tursabActivityPath)) Storage::disk('public')->delete($tursabActivityPath);
            if (isset($tursabRegistryPath)) Storage::disk('public')->delete($tursabRegistryPath);

            return back()->withErrors(['error' => 'Kayıt sırasında bir hata oluştu. Lütfen tekrar deneyin.'])->withInput();
        }
    }
}
