<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;

use App\Models\BaseModel;
use App\Models\Publication;
use App\Models\PublicationReceiver;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class PublicationController extends Controller
{

    protected $model;
    protected $labs;
    protected $publicationReceiverModel;

    public function __construct(Publication $publication){
        $this->model = $publication;
        $this->publicationReceiverModel = new PublicationReceiver();
        $this->baseLabId = Session::get('base_lab_id');
        $this->base = Session::get('base_lab');
    }

    public function index(Request $request){
        $publications = $this->model::query()->whereIn(BaseModel::RECORD_STATUS_FIELD, [RecordStatusEnum::ACTIVE, RecordStatusEnum::DELETE])
            ->when(!empty($request->kword), function ($publications) use($request){
                $publications->whereRaw("replace(title_en, ' ','') like '%".str_replace(" ","",$request->kword)."%'")
                ->orWhereRaw("replace(title_kh, ' ','') like '%".str_replace(" ","",$request->kword)."%'");
            })->orderBy(BaseModel::CREATED_AT_FIELD,'desc')->paginate(config('labis.pagination.perpage', 10));
        return view('publication', ['publications' => $publications, 'labs' => $this->labs]);
    }

    public function save(Request $request){
        try{
            $validator = \Validator::make($request->all(), ['start_date' => 'required', 'title_en' => 'required','lab_ids' => 'required']);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('comment.create_fail'), 'errors' => $validator->errors()->all()]);

            $publication = $this->model::query()->create([
                'title_en' => $request->title_en,
                'title_kh' => $request->title_kh,
                'start_date' => date('Y-m-d', strtotime($request->start_date)),
                'end_date' => date('Y-m-d', strtotime($request->end_date)),
                'description' => $request->description
            ]);

            foreach ($request->lab_ids as $lab_id){
                $this->publicationReceiverModel::query()->create([
                    'publication_id' => $publication->id,
                    'lab_id' => $lab_id,
                    'created_by' => Auth::id()
                ]);
            }

            return response()->json(['success' => true, 'message' => __('comment.create_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('comment.create_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function update(Request $request){
        try {
            $validator = \Validator::make($request->all(), ['start_date' => 'required', 'title_en' => 'required', 'lab_ids' => 'required']);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('comment.update_fail'), 'errors' => $validator->errors()->all()]);
            $data = array(
                'title_en' => $request->title_en,
                'title_kh' => $request->title_kh,
                'start_date' => date('Y-m-d', strtotime($request->start_date)),
                'end_date' => date('Y-m-d', strtotime($request->end_date)),
                'description' => $request->description
            );
            $this->model::query()->where('id', $request->uid)->update($data);
            $this->publicationReceiverModel::query()->where('publication_id', $request->uid)->delete();
            foreach ($request->lab_ids as $lab_id){
                $this->publicationReceiverModel::query()->create([
                    'publication_id' => $request->uid,
                    'lab_id' => $lab_id,
                    'created_by' => Auth::id()
                ]);
            }
            return response()->json(['success' => true, 'message' => __('comment.update_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('comment.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function get(Request $request){
        try{
            $test = $this->model::with(['receivers'])->find($request->uid);
            return response()->json(['success' => true, 'message' => __('comment.get_success'), 'data' => $test]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('comment.get_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function delete(Request $request){
        try{
            $this->model::query()->where('id', $request->uid)->update(array(BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::DELETE));
            return response()->json(['success' => true, 'message' => __('comment.delete_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('comment.delete_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function restore(Request $request){
        try{
            $this->model::query()->where('id', $request->uid)->update(array(BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE));
            return response()->json(['success' => true, 'message' => __('comment.restore_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('comment.restore_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function read($id){
        $publications = $this->model::query()->whereIn(BaseModel::RECORD_STATUS_FIELD, [RecordStatusEnum::ACTIVE, RecordStatusEnum::DELETE])->where('id', $id)->get()->first();
        return view('read_message', ['publications' => $publications]);
    }

}
