<?php

namespace App\Http\Controllers\API\V1;

use App\Demande;
use App\Http\Controllers\Controller;
use App\Offres;
use App\Theme_offre;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OffresController extends Controller
{
    public function index(Request $request)
    {
         try {
            $articles = DB::connection('tenant')->table('offres')->where('status','=','ACTIVE')->get();
            $total = count($articles);
         return response()->json([
             'status' =>  'success',
             'data' => $articles,
             'total'=>$total,
             'message' => 'ARTICLES_GOT_SUCCESSFULLY'
         ], 200);
         } catch (\Exception $e) {
             return response()->json([
                 'status' =>  'error',
                 'message' => $e->getMessage()
             ], 400);
         }
    }
//Recuperation d'une offres
    // public function get_offre($offre_id)
    // {
    //     try {
    //        //  $articles = DB::connection('offres')->table('offres')->join('theme_offres', 'offres.id', '=', 'theme.offre_id')->where('offres.id','=',$offre_id)->first();
    //         return response()->json([
    //          'status' =>  'success',
    //          'data' =>[],
    //          'message' => 'ARTICLES_GOT_SUCCESSFULLY'
    //      ], 200);

    //     } catch (\Exception $th) {
    //          return response()->json([
    //              'status' =>  'error',
    //              'message' => $th->getMessage()
    //          ], 400);
    //     }
    // }

    public function store(Request $request)
    {

           try {
            $oldOffre =DB::connection('tenant')->select('select * from demandes where email_dmd = ? AND offre_id=? AND theme_id=?', [$request->email_dmd,$request->offre_id,$request->theme_id]);

            if($oldOffre){
                return response()->json([
                    'status' => "error",
                    'message' => "Une_erreur_est_survenue"
                ], 403);
            }
            DB::connection('tenant')->insert('insert into demandes(nom_dmd,prenom_dmd,sexe_dmd,
            date_naissance_dmd,lieu_naissance_dmd,nationnalite_dmd,adresse_dmd,num_tel_dmd,
            email_dmd,piece_jointe_dmd,desciption_profil_dmd,motif_status,offre_id,theme_id) values (?,?,?,?,?,?,?,?,?,?,?," ",?,?)',
            [$request->nom_dmd,$request->prenom_dmd,
            $request->sexe_dmd,$request->date_naissance_dmd,
            $request->lieu_naissance_dmd,$request->nationnalite_dmd,
            $request->adresse_dmd,
            $request->num_tel_dmd,
            $request->email_dmd,
            $request->piece_jointe_dmd,
            $request->desciption_profil_dmd,
            $request->offre_id,
            $request->theme_id,
            ]);

             return response()->json([
                 'status' =>  'success',
                'data' =>[],
                'message' => 'OFFRES_SAVE_SUCCESSFULLY'
            ])->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
            //     return response()->json([
            //     'status' =>  'success',
            //     'data' =>$request->get('data'),
            //     'message' => 'ARTICLES_GOT_SUCCESSFULLY'
            // ], 200)->withHeaders([
            //     'Accept' => 'application/json',
            //     'Content-Type' => 'application/json'
            // ]);

           } catch (\Exception $th) {
                return response()->json([
                'status' =>  'error',
                'data' =>[],
                'message' => $th->getMessage()
            ], 200);

           }

    }

    public function show_offre($offres_id)
    {
        try {
            $offre = DB::connection('tenant')->table('offres')->where('id',$offres_id)->first();
            $themes = DB::connection('tenant')->table('theme_offres')->where('offre_id',$offre->id)->where('status','=','ACTIVE')->get();
            return response()->json([
            'status' =>  'success',
            'data' =>['offre'=>$offre,'themes'=>$themes],
            'message' => 'ARTICLES_GOT_SUCCESSFULLY'
        ], 200);
        } catch (\Exception $th) {
            return response()->json([
            'status' =>  'error',
            'data' =>[],
            'message' => 'Une_erreur_est_survenue'
        ], 200);
        }
    }

    public function admin_t_offres()
    {
        try {

            $offres = DB::connection('tenant')->table('offres')
                ->get()
                ->groupBy(['status']);

            return response()->json([
            'status' =>  'success',
            'data' =>$offres,
            'message' => 'ARTICLES_GOT_SUCCESSFULLY'
        ], 200);
        } catch (\Exception $th) {
           return response()->json([
            'status' =>  'error',
            'data' =>[],
            'message' => 'ERROR'
        ], 404);
        }
    }
    public function store_offre(Request $request)
    {
        try {
              $oldOffre =DB::connection('tenant')->select('select * from offres where title = ? ', [$request->titre]);
            if($oldOffre){
                return response()->json([
                    'status' => 'error',
                    'message' => "Cette offre a été déjà enregistrer."
                ], 403)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
             DB::connection('tenant')->insert('insert into offres(title,image,doc,niv_offre,date_debut,date_fin) values (?,?,?,?,?,?)',
                [$request->titre,$request->image,
                $request->doc,$request->niv_offre,
                $request->date_debut,$request->date_fin,
                ]);
            return response()->json([
                'status' =>  'success',
                'data' =>[],
                'message' => 'ARTICLES_GOT_SUCCESSFULLY'
            ], 200);
        } catch (\Throwable $th) {
            return response()->json([
                'status' =>  'error',
                'message' => 'Une erreur est survenue'
            ], 200);
        }

    }
    public function edit_offre(Request $request)
    {
        try {
            if (!isset($request->doc) AND !isset($request->image)) {
                 DB::connection('tenant')->update('update offres set title=?,niv_offre=?,date_debut=?,date_fin=? where id = ?',[$request->title,$request->niv_offre,$request->date_debut,$request->date_fin,$request->offre_id]);
            }
            if (isset($request->doc) AND !isset($request->image)) {
                 DB::connection('tenant')->update('update offres set title=?,doc=?,niv_offre=?,date_debut=?,date_fin=? where id = ?',[$request->title,$request->doc,$request->niv_offre,$request->date_debut,$request->date_fin,$request->offre_id]);
            }
            if (!isset($request->doc) AND isset($request->image)) {
                DB::connection('tenant')->update('update offres set title=?,image=?,niv_offre=?,date_debut=?,date_fin=? where id = ?',[$request->title,$request->image,$request->niv_offre,$request->date_debut,$request->date_fin,$request->offre_id]);
            }
            if (isset($request->doc) AND isset($request->image)) {
                 DB::connection('tenant')->update('update offres set title=?,image=?,doc=?,niv_offre=?,date_debut=?,date_fin=? where id = ?',[$request->title,$request->image,$request->doc,$request->niv_offre,$request->date_debut,$request->date_fin,$request->offre_id]);
            }
            return response()->json([
                    'status' =>  'success',
                    'data' =>[],
                    'message' => 'ARTICLES_GOT_SUCCESSFULLY'
                ], 200);
        } catch (\Throwable $th) {
             return response()->json([
                    'status' =>  'error',
                    'message' => 'Une erreur est survenue'
                ], 200);
        }
    }


    public function action_act_des($status,$offre_id)
    {
         try {
            $reque = DB::connection('tenant')->update('update offres set status = ? where id = ?',[$status,$offre_id]);
            return response()->json([
                    'status' =>  'success',
                    'message' => 'ARTICLES_GOT_SUCCESSFULLY'
                ], 200);
         } catch (\Exception $th) {
              return response()->json([
                    'status' =>  'error',
                    'message' => "Erreur lors de l'activation de l'offre"
                ], 200);
         }
    }


    public function offre_get_datas_edit($offre_id)
    {
          try {
              $offres = DB::connection('tenant')->table('offres')->where('id','=',$offre_id)->first();
                return response()->json([
                    'status' =>  'success',
                    'data' =>$offres,
                    'message' => 'ARTICLES_GOT_SUCCESSFULLY'
                ], 200);
          } catch (\Exception $th) {
                       return response()->json([
                    'status' =>  'error',
                    'message' => 'Une erreur est survenue '
                ], 200);
          }
    }

    public function demande_liste()
    {
        try {
            $demandes = DB::connection('tenant')->table('demandes')
                ->select('demandes.*','demandes.id as demande_id','offres.*','demandes.status as offre_status')
                ->leftJoin('offres', 'demandes.offre_id', '=', 'offres.id')
                ->get()
                ->groupBy('niv_offre');
                 return response()->json([
                    'status' =>  'success',
                    'data' =>$demandes,
                    'message' => 'ARTICLES_GOT_SUCCESSFULLY'
                ], 200);
        } catch (\Exception $th) {
             return response()->json([
                    'status' =>  'error',
                    'message' => 'UNE_ERREUR_EST_SURVENUE'
                ], 404);
        }
    }

    public function demande_offre_theme($offre,$theme)
    {
         try {
             $offre = DB::connection('tenant')->table('offres')->where('offres.id',$offre)->get()->first();
             $theme = DB::connection('tenant')->table('theme_offres')->where('theme_offres.id',$theme)->get()->first();
             return response()->json([
                    'status' =>  'success',
                    'data' =>['offre'=>$offre,'theme'=>$theme],
                    'message' => 'ARTICLES_GOT_SUCCESSFULLY'
                ], 200);
         } catch (\Exception $th) {
             return response()->json([
                    'status' =>  'success',
                    'data' =>$th,
                    'message' => 'ARTICLES_GOT_SUCCESSFULLY'
                ], 200);
         }
    }

    public function demande_show($demande_id)
    {
        try {

            $demandes = DB::connection('tenant')->table('demandes')
            ->select('demandes.*','demandes.id as demande_id','offres.title as offre_title','offres.image as offre_image','offres.doc as offre_doc','offres.niv_offre as niv_offre','offres.status as offre_status','offres.date_debut as date_debut','offres.date_fin as date_fin','demandes.status as demande_status')
            ->join('offres','demandes.offre_id','=','offres.id')
            ->where('demandes.id',$demande_id)->first();



           // $theme = DB::connection('tenant')->table('theme_offres')->where('id','=',$demandes->theme_id)->first();
            $theme = ($demandes->theme_id!=0)? DB::connection('tenant')->table('theme_offres')->where('id','=',$demandes->theme_id)->first():[];

                 return response()->json([
                    'status' =>  'success',
                    'data' =>['demande'=>$demandes,'theme'=>$theme],
                    'message' => 'OFFERS_GOT_SUCCESSFULLY'
                ], 200);
        } catch (\Exception $e) {
              return response()->json([
                    'status' =>  'error',
                    'data'=>$e->getMessage(),
                    'message' => 'UNE_ERREUR_EST_SURVENUE'
                ], 404);
        }
    }

     public function destroy(Request $request, $id)
    {
        try {
            // $offres = Offres::on('tenant')->findOrFail($id);
            Demande::on('tenant')->where('offre_id', '=', $id)->delete();
            Theme_offre::on('tenant')->where('offre_id', '=', $id)->delete();
            Offres::on('tenant')->where('id', $id)->delete();
             return response()->json([
                'status' => 'success',
                // 'data'=>['offre'=>$offres,'demandes'=>$demande],
                'message' => "OFFERS_DELETED_SUCCESSFULY"
            ], 200)->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage()
            ], 404)->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
        }
    }

    public function theme_store(Request $request)
    {
        try {

             $oldOffre =DB::connection('tenant')->select('select * from theme_offres where title = ? AND description=? AND offre_id=?', [$request->title,$request->description,$request->offre_id]);

            if($oldOffre){
                return response()->json([
                    'status' => 'error',
                    'message' => "Cet theme existe déjà pour cette offre."
                ], 403)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

            DB::connection('tenant')->insert('insert into theme_offres(title,offre_id,description,status) values (?,?,?,"ACTIVE")',
            [$request->title,$request->offre_id,
            $request->description,
            ]);
            return response()->json([
                    'status' =>  'success',
                    'message' => 'THEME_GOT_SUCCESSFULLY'
                ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' =>  'error',
                'message' => 'UNE_ERREUR_EST_SURVENUE'
            ], 200);
        }
    }

    public function demande_decision(Request $request)
    {
         try {
             DB::connection('tenant')->update('update demandes set status = ?, motif_status=? where id = ?',[$request->status,$request->description,$request->demande_id]);
             $demande_offre = DB::connection('tenant')
                            ->table('demandes')
                            ->select('demandes.*','demandes.id as demandes_id','offres.id as offre_id','offres.title as offre_title','offres.niv_offre as offre_niv_offre')
                            // ->select('demandes.*','demandes.id as demandes_id','theme_offres.title as theme_title','theme_offres.description as theme_description','theme_offres.id as theme_id','offres.id as offre_id','offres.title as offre_title','offres.niv_offre as offre_niv_offre')
                            ->join('offres','demandes.offre_id','=','offres.id')
                            ->where('demandes.id',$request->demande_id)
                            ->first();

            $theme = DB::connection('tenant')
                            ->table('demandes')
                            ->select('demandes.*','demandes.id as demandes_id','theme_offres.title as theme_title','theme_offres.description as theme_description','theme_offres.id as theme_id')
                            ->join('theme_offres','demandes.offre_id','=','theme_offres.id')
                            ->where('demandes.id',$request->demande_id)
                            ->first();

             return response()->json([
                    'status' =>  'success',
                    'data'=>['demande_offre'=>$demande_offre,'theme'=>$theme],
                    'message' => 'ARTICLES_GOT_SUCCESSFULLY'
                ], 200);
         } catch (\Exception $th) {
              return response()->json([
                    'status' =>  'error',
                    'data'=>$th,
                    'message' => "Erreur lors de la prise de décision "
                ], 200);
         }
    }
}


