<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Inscription;
use App\Models\Company;
use App\Models\CompanyCategory;

class InscriptionController extends Controller
{
    public function index(Request $request)
    {
        $query = !empty($request->get('q')) ? $request->get('q') : null;
        if ($query) {
            $inscriptions = Inscription::where('confirmed', 0)->search($query, null, true)->paginate(20);
        } else {
            $inscriptions = Inscription::where('confirmed', 0)->paginate(20);
        }
        return view('backend.inscriptions.index', compact('inscriptions'));
    }

    public function delete($id)
    {
        $inscription = Inscription::find($id);
        $inscription->delete();

        return redirect()->route('backend.inscriptions.index');
    }

    public function createCompany($id)
    {
        $inscription = Inscription::find($id);
        $company = Company::create([
            'name'          => $inscription->company_name,
            'email'         => $inscription->email,
            'site'          => $inscription->company_site,
            'prenom'        => $inscription->prenom,
            'nom'           => $inscription->nom,
            'phone'         => $inscription->phone,
            'country_id'    => $inscription->country_id,
        ]);

        $company->slug = str_slug($inscription->company_name, '-');
        $company->save();

        CompanyCategory::create([
            'company_id'    => $company->id,
            'category_id'   => $inscription->category_id
        ]);

        $inscription->confirmed = 1;
        $inscription->save();
        
        return redirect()->route('backend.companies.show', $company->id);
    }
}
