<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Company;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;

use App\Http\Controllers\Mailgun\MailgunController;

class CompanyController extends Controller
{
    public function getCompanyInfo()
    {
        Session::forget('user_id');
        return view('company.company-info');
    }

    public function storeCompany(Request $request)
    {
        
        if(Session::has('user_id') || Auth::id()) {
            
         $messages = [
            'company_domain.unique' => 'The domain has already been registered.',
            'company_domain.regex' => 'Please enter a valid domain format, e.g., example.com (without https and /)'
        ];
        
        $this->validate($request, [
            'company_name' => 'required|string|max:255',
            'company_email' => 'required|email',
            'company_domain' => [
                'required',
                'regex:/^([a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+)$/',  // Updated regex
                'unique:companies,domain'
            ],
        ], $messages);


            $company = Company::updateOrCreate([
                'user_id' => Session::has('user_id') ? Session::get('user_id') : Auth::id(),
            ],[
                'user_id' => Session::has('user_id') ? Session::get('user_id') : Auth::id(),
                'name' => $request->company_name,
                'email' => $request->company_email,
                'about' => $request->about,
                'domain' => $request->company_domain,
            ]);
            
            Session::put('selected_company', $company->id);
            
            $MailgunController = new MailgunController();
            
            return $MailgunController->addDomain($request->company_domain);

        if(Session::has('user_id'))
            return redirect()->route('login.create')->with('success', 'Register Successfully');
        }
        
        return redirect('/dashboard');
    }
}
