<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\ProfileUpdateRequest;
use App\Http\Requests\ProfileStoreRequest;
use App\Http\Requests\ProfileDeleteRequest;
use Exception;
use Illuminate\Support\Facades\DB;
//use App\Key;
use App\Profile;


class ProfileController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ProfileStoreRequest $request)
    {
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }


    public function showProfil(Request $request,$user_matricule=null){

        try {

            $user_matricule = $user_matricule != null ? $user_matricule : $request->get('User')['matricule'];

            $profil_site = DB::connection('tenant')
                ->table('profiles')
                ->where('user_matricule','=',$user_matricule)
                ->get()->first();

            $type_user = DB::connection('tenant')
                ->table('users')
                ->where('matricule','=',$user_matricule)
                ->select('type_user')->first();

            if($type_user){

                $type_user = $type_user->type_user;

                if($type_user == 0){

                    $server_response = getFromGest('api/v1/userStudents/'.$user_matricule.'/profile', ['bd' => substr(hackKey(false,$request->bd), 5)])->json();

                    if(array_key_exists('success', $server_response) && $server_response['success'] == true){

                        $profil_gest = $server_response['data'];

                        $statut_soutenu = DB::connection('tenant')
                            ->table('theme_user')
                            ->where('theme_user.user_matricule','=',$user_matricule)
                            ->where('theme_user.statut','=','TAKEN')
                            ->join('themes','theme_user.theme_id','=','themes.id')
                            ->where('themes.statut','=','SOUTENU')
                            ->get()->first();

                        if($statut_soutenu){
                            $statut_soutenu = true;
                        }
                        else{
                            $statut_soutenu = false;
                        }

                        return response()->json([
                            'status' => 'success',
                            'profil_site' => $profil_site,
                            'profil_gest' => $profil_gest['profil'],
                            'filiere' => $profil_gest['filiere'],
                            'username' => $profil_gest['username'],
                            'soutenu' => $statut_soutenu
                        ])->withHeaders([
                            'Accept' => 'application/json',
                            'Content-Type' => 'application/json'
                        ]);
                    }
                    else{

                        return response()->json([
                            'status' => 'error',
                            'message' => $server_response['message']
                        ])->withHeaders([
                            'Accept' => 'application/json',
                            'Content-Type' => 'application/json'
                        ]);
                    }
                }
                else{

                    $server_response = getFromGest('api/v1/users/'.$user_matricule.'/profile', ['bd' => substr(hackKey(false,$request->bd), 5)])->json();

                    if(array_key_exists('success', $server_response) && $server_response['success'] == true){

                        $profil_gest = $server_response['data'];

                        return response()->json([
                            'status' => 'success',
                            'profil_site' => $profil_site,
                            'profil_gest' => $profil_gest['profil'],
                            'username' => $profil_gest['username'],
                        ])->withHeaders([
                            'Accept' => 'application/json',
                            'Content-Type' => 'application/json'
                        ]);
                    }
                    else{

                        return response()->json([
                            'status' => 'error',
                            'message' => $server_response['message']
                        ])->withHeaders([
                            'Accept' => 'application/json',
                            'Content-Type' => 'application/json'
                        ]);
                    }
                }

            }
            else{
                return response()->json([
                    'status' => 'error',
                    'message' => 'NO_DATA_FOR_THIS_MATRICULE'
                ])->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 cdProfil(Request $request){

        try {

            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];

            $server_response = getFromGest('api/v1/departements/'.$departement.'/cd/profile', ['bd' => substr(hackKey(false,$request->bd), 5)])->json();

            if(array_key_exists('success', $server_response) && $server_response['success'] == true){

                $profil = $server_response['data'];

                return response()->json([
                    'status' => 'success',
                    'profil' => $profil[0],
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
            else{
                return response()->json([
                    'status' => 'error',
                    'message' => $server_response['message']
                ])->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'
            ]);
        }
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ProfileUpdateRequest $request, $id)
    {

        try {

            $User= $request->get('User');
            //Mettre à jour le profil
            $profile = Profile::on('tenant')->findOrFail($id);

            //Verifier si l'utilisateur est autorisé à modifier ce profil
            if (Profile::on('tenant')->findOrFail($id)->get()->first()->user_matricule == $User->matricule) {

                if (isset($request->photo)) {
                    $profile->photo = $request->photo;
                }
                if (isset($request->ville)) {
                    $profile->ville = $request->ville;
                }
                if (isset($request->lieu_de_travail)) {
                    $profile->lieu_de_travail = $request->lieu_de_travail;
                }
                if (isset($request->contact_email)) {
                    $profile->contact_email = $request->contact_email;
                }
                if (isset($request->contact_whatsapp)) {
                    $profile->contact_whatsapp = $request->contact_whatsapp;
                }
                if (isset($request->contact_tweeter)) {
                    $profile->contact_tweeter = $request->contact_tweeter;
                }
                if (isset($request->contact_facebook)) {
                    $profile->contact_facebook = $request->contact_facebook;
                }
                if (isset($request->promotion)) {
                    $profile->promotion = $request->promotion;
                }
                if (isset($request->bio)) {
                    $profile->bio = $request->bio;
                }

                //$profile->user_matricule = $request->user_matricule;


                if (isset($request->statut)) {

                    //On vérifie si le statut de la requete est valide
                    $statut_array = ['PUBLISHED', 'BLOCKED', 'PENDING', 'SIGNALED'];
                    foreach ($statut_array as $statut) {

                        if ($request->statut == $statut) {

                            $profile->statut = $request->statut;
                        }
                    }

                    return response()->json([
                        'status' => 'error',
                        'message' => 'This statut does not exist.'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }

                $profile->update();

                return response()->json([
                    'status' => 'success',
                    'profil' => $profile
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
            return response()->json([
                'status' => 'error',
                'message' => "Permissions not granted"
            ])->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'
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(ProfileDeleteRequest $request, $id)
    {
        try {

            //$key = Key::all()->where('api_key', '=', $request->header('Authorization'))->first();

            $User= $request->get('User');
            //On récupère le profil
            $profile = Profile::on('tenant')->findOrFail($id);

            //Verifier si l'utilisateur est autorisé à supprimer ce profil
            if (Profile::on('tenant')->findOrFail($id)->get()->first()->user_matricule == $User->matricule) {

                if ($request->mode == "soft") {

                    $profile->statut = 'DELETED';
                    $profile->update();

                    return response()->json([
                        'status' => 'success',
                        'article' => 'SOFT_DELETE_DONE'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                } else if ($request->mode == "strict") {

                    $profile->delete();
                    return response()->json([
                        'status' => 'success',
                        'page' => 'STRICT_DELETE_DONE'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                } else {

                    return response()->json([
                        'status' => 'error',
                        'message' => 'This mode does not exist.'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }
            }

            return response()->json([
                'status' => 'error',
                'message' => "Permissions not granted"
            ])->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'
            ]);
        }
    }
}
