<?php

namespace App\Http\Controllers\Admin;

use App\DataTables\WeeklyProgramsDataTable;
use App\Events\NewWeeklyProgram;
use App\Http\Controllers\Controller;
use App\Models\Division;
use App\Models\WeeklyProgram;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class WeeklyProgramsController extends Controller
{
    //
    // public function weeklyProgram()
    // {
    //     return view('admin.weeklyProgram.weeklyProgram-index');
    // }


    public function weeklyPrograms(WeeklyProgramsDataTable $weeklyProgramsDataTable)
    {
        return $weeklyProgramsDataTable->render('admin.weeklyPrograms.weeklyPrograms-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', WeeklyProgram::class)) {
            foreach ($divisions as $key => $division) {
                if (Auth::guard('admin')->user()->cannot('manageDivision', [WeeklyProgram::class, $division])) {
                    unset($divisions[$key]);
                }
            }
        }

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


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

        $path = $request->file('attachments')->store('attachments');
        $validatedData['attachments'] = $path;

        $validatedData['user_id'] = Auth::guard('admin')->user()->id;

        WeeklyProgram::create($validatedData);

        
        event(new NewWeeklyProgram($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\WeeklyProgram,id'],
        ], [], [])->validate();
        $weeklyProgram = WeeklyProgram::find($id);

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

        $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', WeeklyProgram::class)) {
            foreach ($divisions as $key => $division) {
                if (Auth::guard('admin')->user()->cannot('manageDivision', [WeeklyProgram::class, $division])) {
                    unset($divisions[$key]);
                }
            }
        }

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

    public function update(Request $request)
    {

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

        $weeklyProgram = WeeklyProgram::find($validatedData['id']);

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

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

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

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


    public function delete(Request $request)
    {

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

        $weeklyProgram = WeeklyProgram::find($data['weeklyProgram_id']);
        $this->authorize('manage', $weeklyProgram);

        try {
            $weeklyProgram->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'));
        }
    }
}
