<?php

namespace App\Http\Controllers\Admin;

use App\Models\Division;
use App\Models\Worksheet;
use App\Models\StudentNote;
use App\Events\NewWorksheet;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\DataTables\WorksheetsDataTable;
use Illuminate\Support\Facades\Validator;

class WorksheetsController extends Controller
{
    //

    public function worksheets(WorksheetsDataTable $worksheetsDataTable)
    {
        return $worksheetsDataTable->render('admin.worksheets.worksheets-index');
    }

    public function showCreateView()
    {

        $divisions = Division::select('divisions.id', 'divisions.title', 'levels.title as level', 'stages.title as stage')
            ->join('levels', 'levels.id', '=', 'divisions.level_id')
            ->join('stages', 'stages.id', '=', 'levels.stage_id')->get();

        if (Auth::guard('admin')->user()->cannot('manageAsSuper', Worksheet::class)) {
            foreach ($divisions as $key => $division) {
                if (Auth::guard('admin')->user()->cannot('manageDivision', [Worksheet::class, $division])) {
                    unset($divisions[$key]);
                }
            }
        }

        return view('admin.worksheets.worksheets-create', ['divisions' => $divisions]);
    }


    public function create(Request $request)
    {
        $data = ($request->all());
        $validatedData = Validator::make($data, [
            'title' => ['required', 'max:255'],
            'division_id' => ['required', 'max:255', 'exists:App\Models\Division,id'],
            'description' => ['max:10240'],
            'attachments' => ['required', 'file', 'max:10240'],
        ], [], [])->validate();

        $path = $request->file('attachments')->store('attachments');
        $validatedData['attachments'] = $path;
        $validatedData['user_id'] = Auth::guard('admin')->user()->id;

        Worksheet::create($validatedData);

        event(new NewWorksheet($validatedData['division_id']));

        return back()->with('success', trans('general.record_added_successfully'));
    }



    public function showUpdateView($id)
    {

        Validator::make(['id' => $id], [
            'id' => ['required', 'max:255', 'exists:App\Models\Worksheet,id'],
        ], [], [])->validate();
        $worksheet = Worksheet::find($id);

        $this->authorize('manage', $worksheet);

        $divisions = Division::select('divisions.id', 'divisions.title', 'levels.title as level', 'stages.title as stage')
            ->join('levels', 'levels.id', '=', 'divisions.level_id')
            ->join('stages', 'stages.id', '=', 'levels.stage_id')->get();

        if (Auth::guard('admin')->user()->cannot('manageAsSuper', Worksheet::class)) {
            foreach ($divisions as $key => $division) {
                if (Auth::guard('admin')->user()->cannot('manageDivision', [Worksheet::class, $division])) {
                    unset($divisions[$key]);
                }
            }
        }

        return view('admin.worksheets.worksheets-edit', ['worksheet' => $worksheet, 'divisions' => $divisions]);
    }

    public function update(Request $request)
    {

        $data = ($request->all());
        $validatedData = Validator::make($data, [
            'id' => ['required', 'max:255', 'exists:App\Models\Worksheet,id'],
            'title' => ['required', 'max:255'],
            'description' => ['max:10240'],
            'division_id' => ['required', 'max:255', 'exists:App\Models\Division,id'],
            'attachments' => ['file', 'max:10240'],
        ], [], [])->validate();
        $validatedData['user_id'] = Auth::guard('admin')->user()->id;

        $worksheet = Worksheet::find($validatedData['id']);

        $this->authorize('manage', $worksheet);

        if (isset($validatedData['attachments'])) {
            $path = $request->file('attachments')->store('attachments');
            $validatedData['attachments'] = $path;
            $worksheet->attachments = $validatedData['attachments'];
        }

        $worksheet->title = $validatedData['title'];
        $worksheet->user_id = $validatedData['user_id'];
        $worksheet->description = $validatedData['description'];
        $worksheet->division_id = $validatedData['division_id'];
        $worksheet->save();

        return back()->with('success', trans('general.record_updated_successfully'));
    }


    public function delete(Request $request)
    {

        $data = $request->all();
        Validator::make($data, [
            'worksheet_id' => ['required', 'max:190', 'exists:App\Models\Worksheet,id'],
        ], [], [])->validate();

        $worksheet = Worksheet::find($data['worksheet_id']);
        $this->authorize('manage', $worksheet);

        try {
            $worksheet->delete();
            return back()->with('success', trans('general.record_deleted_successfully'));
        } catch (\Illuminate\Database\QueryException $th) {
            return back()->withErrors(trans('general.record_foreign_key_delete_error'));
        } catch (\Throwable $th) {
            return back()->withErrors(trans('general.record_delete_error'));
        }
    }
}
