<?php

namespace App\Http\Controllers\API\v1;

use App\Article;
use App\Attachement;
use App\Http\Controllers\Controller;
use App\Http\Requests\AttachementUpdateRequest;
use App\Key;
use App\Log;
use App\User;
use Exception;
use Illuminate\Http\Request;

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

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

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(AttachementUpdateRequest $request, $id)
    {
        try {
            //$key = Key::all()->where('api_key', '=', $request->header('Authorization'))->first();

            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;
            $User= $request->get('User');

            //Update of the attachement
            $attachement = Attachement::on('tenant')->findOrFail($id);

            //Verify if the user requesting is the owner of the article bound
            if (Article::on('tenant')->findOrFail($attachement->article_id)->get()->first()->user_matricule == $User->matricule) {
                if (isset($request->nom)) {
                    $attachement->nom = $request->nom;
                }

                if (isset($request->url)) {
                    $attachement->url = $request->url;
                }

                $attachement->update();

                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'ATTACHEMENT UPDATE';
                $log->description = json_encode($attachement);
                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'success',
                    'attachement' => $attachement
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            } else {
                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'ATTACHEMENT UPDATE';
                $log->description = 'PERMISSIONS NOT GRANTED';
                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'error',
                    'message' => "Permissions not granted"
                ], 403)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {
            //Sauvegarder l'opération
            $log = new Log();
            $log->bd = $bd;
            $log->operation = 'ATTACHEMENT UPDATE';
            $log->description = $e->getMessage();
            $log->user_matricule = $User->matricule;
            $log->save();

            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(Request $request, $id)
    {
        try {
            //$key = Key::all()->where('api_key', '=', $request->header('Authorization'))->first();
            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;

            $User= $request->get('User');

            //Get the attachement
            $attachement = Attachement::on('tenant')->findOrFail($id);

            //Get related article
            $article = Article::on('tenant')->where('id', '=', $attachement->article_id)->get()->first();

            //Verify if the user requesting is the owner of the article
            if ($article->user_matricule == $User->matricule) {
                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'ATTACHEMENT DELETE';
                $log->description = json_encode($attachement);

                $attachement->delete();

                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'success',
                    'message' => 'ATTACHEMENT_DELETE'
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            } else {
                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'ATTACHEMENT DELETE';
                $log->description = 'PERMISSIONS NOT GRANTED';
                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'error',
                    'message' => "Permissions not granted"
                ], 403)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {
            //Sauvegarder l'opération
            $log = new Log();
            $log->bd = $bd;
            $log->operation = 'ATTACHEMENT DELETE';
            $log->description = $e->getMessage();
            $log->user_matricule = $User->matricule;
            $log->save();

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