<?php

namespace App\Http\Controllers;

use App\Models\Contrat;
use App\Models\ContratFreqPay;
use App\Models\FreqPay;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use RealRashid\SweetAlert\Facades\Alert;

class ContratFreqPayController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $freqPay =FreqPay::all();
        $contrat = Contrat::all();
        return view('Admin.pages.File_ContratFreqPay.ContratFreqPay',compact('freqPay','contrat'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $donnees = DB::table('contrat_freq_pays')
    ->join('contrats', 'contrat_freq_pays.contrat_id', '=', 'contrats.id')
    ->join('freq_pays', 'contrat_freq_pays.freqPay_id', '=', 'freq_pays.id')
    ->select(
        'contrat_freq_pays.id',
        'contrats.codeContrat',
        'freq_pays.nomFreqPay',
        'contrat_freq_pays.montnat'
    )
    ->get();

        // Remplacez "VotreModele" par le nom de votre modèle de données

    return response()->json($donnees);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = array(
            'contrat_id' => 'required',
            'freqPay_id' => 'required',
            'montnat' => 'required',
        );

        $error = Validator::make($request->all(), $rules);

        if ($error->fails()) {
            Alert::toast('Add success','success');

            return redirect()->back()->withErrors($error)->withInput();
        }

        try {
            $form_data = array(

                'contrat_id' => $request->contrat_id,
                'freqPay_id' => $request->freqPay_id,
                'montnat'=> $request->montnat,

            );
            ContratFreqPay::create($form_data);
            Alert::toast('Add success','success');
            return redirect()->back()->withInput();
        } catch (\Illuminate\Database\QueryException $exception) {
        Alert::toast('Une erreur s\'est produite lors de l\'ajout','error' /*. $exception->getMessage()*/);
            return redirect()->back()->withInput();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\GestionUnite  $gestionUnite
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {


    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\GestionUnite  $gestionUnite
     * @return \Illuminate\Http\Response
     */
      public function edit($id)
    {
        $ContratFreqPay = ContratFreqPay::find($id);
        return response()->json([
            'status' => 200,
            'ContratFreqPay' => $ContratFreqPay,
        ]);
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\GestionUnite  $gestionUnite
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        //la route update a été détacher de la route ressource  (faite un php artisan route:list)
        $ContratFreqPay_id = $request->input('id');
        $ContratFreqPay = ContratFreqPay::find($ContratFreqPay_id);
        try {
            $ContratFreqPay->contrat_id = $request->input('contrat_id');
            $ContratFreqPay->freqPay_id = $request->input('freqPay_id');
            $ContratFreqPay->montnat = $request->input('montnat');
            $ContratFreqPay->update();
            Alert::toast('Update success','success');
            return redirect()->route('Contrats+FreqPay.index');
        } catch (\Illuminate\Database\QueryException $exception) {
            Alert::toast('Veuillez rempli tous champs','error');
            return redirect()->back()->withInput();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\GestionUnite  $gestionUnite
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {

        $data_id = $request->input('deleteContratFreqPay');
        $data = ContratFreqPay::find($data_id);

        try {
            $data->delete();
            Alert::toast('Delete success','success');
        } catch (\Illuminate\Database\QueryException $exception) {
            $errorInfo = $exception->errorInfo;

            if ($errorInfo[0] === '23000' && $errorInfo[1] === 1451) {
                $affectedTables = $this->getAffectedTables($errorInfo[2]);
                $errorMessage = "Impossible de supprimer l'événement. Il est référencé dans les tableaux suivants : " . implode(", ", $affectedTables);
                Alert::toast($errorMessage,'error');
            } else {
                Alert::toast($exception->getMessage(),'error');
            }
        }

        return  redirect()->back()->withInput();
    }

    private function getAffectedTables($errorMessage)
    {
        preg_match_all("/`(.+?)`/", $errorMessage, $matches);
        return $matches[1];
    }
}
