<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\DepartementStoreRequest;

use App\Services\RandomFiliereService;
use App\Services\ExamStuffService;

class TenantController extends Controller
{

    public function store(Request $request)
    {
    	try { // etablissement_id departement_id software_id bd custom_domain subdomain identification_path client_key
				// Process the full url
				$software = $request->get('Software');
				$tenant = $request->tenant;
				$tenant['software_id'] = $software->id;
//    				$tenant['subdomain'] = ;// generate a subdomain unique
				$tenant['client_key'] = gen_client_key();// generate a client_key

				DB::table('customer_software')->insert($tenant);
	            return sendResponse([], "DATA_GOT_SUCCESSFULLY");

		    } catch (Exception $e) {
				return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 400);
		    }

    }

    public function load_tenant(Request $request)
    {
    	try { // Can also check here if status of customer is not blocked
			// Process the full url
			$tenant = $request->tenant;
			// Get software id software
      	    $software = $request->get('Software');//DB::table('softwares')->where('subdomain', $tenant['software'])->first();
			//return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $request->get('Software'));
      	    $check_tenant = DB::table('customer_software')->select('status', 'client_key', 'enable_custom_domain', 'etablissement_id', 'departement_id','folder_disk')->where([
      	    ['subdomain', $tenant['identifier']], ['software_id', $software->id] ])->first();

			if ($check_tenant) {
				if ($check_tenant->status == 'PUBLISHED') {
					$client = [];
					$client['client_id'] = $check_tenant->client_key;// must be encrypted
					$client['departement_id'] = $check_tenant->departement_id;
					$client['isForSchool'] = in_array($check_tenant->departement_id,[null,1000000]) ? true : false;
					$client['schools_info'] = [];
					$client['disk'] = $check_tenant->folder_disk;
					$etablissement_id = $check_tenant->etablissement_id;


					$etablissement = DB::table('etablissement')->where('idEtablissement', $etablissement_id)->first();
                    $bd = $etablissement->namebase;
                    if(changeEnv(['database'  => $bd ])){
    					$etablissements = DB::connection('tenant')->table('etablissement')->select('idEtablissement as id_etablis','nameimgeta',"sigleeta","descreta", "ville","adresse","dureeValideCarte","choixTemp", "dateDepart","message","couleur","slogan","couleur2","couleur3");
    					 $mes_etablissements = DB::table('universite')->select('idUniversite as id','nameimguni as nameimgeta',"sigle as sigleeta","descruni as descreta");
    					 $client['schools_info']['all'] = $mes_etablissements->where('partenaire', 'YES')->orderBy('id','asc')->get();
						 $client['schools_info']['current'] = $etablissements->where('idEtablissement', $etablissement_id)->first();

                        // for new index page
                            $client['schools_info']['current']->{'email'} = $etablissement->email;
                            $client['schools_info']['current']->{'phone_number'} = '+229 97979797'; // to make dynamic

                            $annee_acad = current_acad();

                            // get all ecs for some later requests
                            $all_ecs = DB::connection('tenant')
                            ->table('ecu')
                            ->where('annee_acad', '=', $annee_acad)
                            ->get();

                            // nombre d'enseignant faisant cours pour l'année courante
                            $prof_matricules = $all_ecs->pluck("matricule")
                            ->toArray();
                            $nb_enseignant =  count(array_unique($prof_matricules));

                            // nombre d'etudiants inscrits durant l'année academique en cours
                            $nb_etu = DB::connection('tenant')->table('tabinscription')
                            ->where('annee_acad','=',$annee_acad)
                            ->count();

                            $total_members = $nb_enseignant + $nb_etu;

                            $client['schools_info']['current']->{'total_members'} = $total_members;
                            $client['schools_info']['current']->{'total_evals'} = ExamStuffService::get_total($annee_acad);


						 $acad = DB::connection('tenant')->table('periodeinscription')->where('affiche', 'YES')->select('annee_acad')->first();
						 $client['schools_info']['current_year'] = $acad->annee_acad;

    					return sendResponse($client, "DATA_GOT_SUCCESSFULLY");
                    } else {
                        return sendError("impossible de balancer la connection, veuillez contacter les administrators");
                    }

				} else {
					return sendError("RESSOURCE NOT AVAILABLE FOR YOUR SCHOOL, PLEASE CONTACT ADMINISTRATOR");
				}
			}
			return sendError("WRONG IDENTIFICATION DATA, PLEASE CONTACT ADMINISTRATOR FOR MORE DETAILS");
      	} catch (Exception $e) {
			return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 400);
      	}

    }

	public function tenant_access(Request $request)
    {
    	try {

				$client = $request->get('Client');
				$tenant = $request->tenant;
				// Get software id software
				// $request->get('User')['matricule']
				$data = [];
				$data['bd'] = $client->bd;
				$data['client'] = $client;
				return sendResponse($data, "DATA_GOT_SUCCESSFULLY");
      	} catch (Exception $e) {
            return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 400);
      	}

    }


	public function generate_database(Request $request)
    {
    	try {
				$software = $request->get('Software');
				$prefix = $software->db_prefix;
				$bd = $prefix.$request->newdbname;
				$bd = gen_bd_name($bd);
				$success = [];
				$success['bd'] = $bd;
				return sendResponse($success, "DATA_GOT_SUCCESSFULLY");
			} catch (Exception $e) {
				return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 400);
			}

    }


    public function store_site(DepartementStoreRequest $request)
    {
        try {
            //New key for the department
        		$software = $request->get('Software');
        		$front_id = $software->id;

            //Recupérer les informations sur l'école et sur le département depuis GestApi
            $schoolData = $request->get('School');
            // Check if has school already exist
            $schoolExist = DB::table('customer_software')->where('etablissement_id', $schoolData['idEtablissement'])
            ->where('software_id', $front_id)
            ->get()->count();
            //Add key generated in main keys table to link department to university

            if (DB::table('customer_software')->where('etablissement_id', $schoolData['idEtablissement'])
            ->where('departement_id', $request->idDepartement)
            ->where('software_id', $front_id)
            ->get()->count() == 1
            ) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Une cle existe deja pour ce projet'

                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            } else {

								$prefix = $software->db_prefix;
								$bd = $prefix.$schoolData['bd'];
								$bd = gen_bd_name($bd);
								// For disk
								$disk = $schoolData['bd'];
								$disk = gen_disk_name($disk);

								$random_key = gen_client_key();
								// must add disk generation
                $data_to_insert = [
            				"etablissement_id"=>$schoolData['idEtablissement'],
							      "departement_id"=>$request->idDepartement,
							      "software_id"=>$front_id,
							      "bd"=>$bd,
							      "folder_disk"=>$disk,
							      "client_key" => $random_key
					      ];

					      if (isset($request->custom_domain)) {
					      	  $tenant_url = $request->custom_domain;
					          $data_to_insert = array_merge($data_to_insert,["custom_domain"=>$request->custom_domain,"enable_custom_domain"=>1]);
					      } elseif (isset($request->subdomain)){
					      	  $tenant_url = $request->subdomain.".".$software->subdomain;
					      	  $data_to_insert = array_merge($data_to_insert,["subdomain"=>$request->subdomain]);
					      }

								DB::table('customer_software')->insertGetId($data_to_insert);
								$urls = $software->redirect_uri;
								$tenant_url = $tenant_url."/auth";
								$new_urls = array_merge(json_decode($urls,true),[$tenant_url]);
								DB::table('softwares')->where('id', $software->id)->update(['redirect_uri' => json_encode($new_urls)]);
                return response()->json([
                    'status' => 'success',
                    'data' => [
                        'api_key' => $random_key,
                        'bd' => $bd,
                        'schoolExist' => $schoolExist,
                    ],
                    'message' => 'KEY_GENERATED'

                ])->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'
            ]);
        }
    }

}
