<?php

namespace App\Http\Controllers;

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

class BaseController extends Controller
{

    /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function sendResponse($result, $message, $code = 200)
    {
        $response = [
            'success' => true,
            'data' => $result,
            'message' => $message,
        ];

        return response()->json($response, $code);
    }

    /**
     * return error response.
     *
     * @return \Illuminate\Http\Response
     */
    public function sendError($error, $errorMessages = [], $code = 400)
    {
        $response = [
            'success' => false,
            'data' => [],
            'message' => $error,
        ];

        if (!empty($errorMessages)) {
            $response['message'] = $errorMessages;
        }

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

    public function elearningIndex(Request $request){
        try {
            $req = reqGest('GET','v1/elearning/index', [], 2);
            if($req && $req['success']) {

                // add number of media of current year to stats array
                $req["data"]["stats"]["nb_media"] = DB::connection('tenant')
                ->table('medias')
                ->whereIn('ecu_id',$req["data"]["meta"]["ecs_id"])
                ->count();

                // let's remove the "meta" key !
                unset($req["data"]["meta"]);

                return sendResponse($req["data"], "DATA_GOTTEN");
            } else {
                return sendError("ERR_FROM_GESTSTUDENT",[$req], 500);
            }
        } catch (Exception $e) {
            return sendError("ERR_FROM_GESTSTUDENT",$e->getMessage(), 500);
        }
    }

    public function filterFilieres(Request $request){
        try {
            $req = reqGest('POST','v1/filieres/filter', [
                'departement' => $request->departement,
                'domaine' => $request->domaine,
                'mention' => $request->mention,
            ], 2);
            if($req && $req['success']) {
                return sendResponse($req["data"], "DATA_GOTTEN");
            } else {
                return sendError("ERR_FROM_GESTSTUDENT",[$req], 500);
            }
        } catch (Exception $e) {
            return sendError("ERR_FROM_GESTSTUDENT",$e->getMessage(), 500);
        }
    }
}
