<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\HomeWork;
use App\Models\Student;
use Devrabiul\ToastMagic\Facades\ToastMagic;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class HomeWorkController extends Controller
{
    public function __construct() {
        $this->middleware("role:admin,teacher,trainer")->only(['index', 'changeStatus']);
        $this->middleware("role:student")->only(['studentWorks','storeStudentWorks']);
    }
    public function index(){
        $data['title'] = "Work Submissions";
        $user = Auth::user()->load(['trainer', 'teacher']);
        $query = HomeWork::query()->with(['course:id,name', 'user:id,name,phone']);
        if(in_array($user->role, ['teacher', 'trainer'])){
            $students = Student::where($user->role.'_id', $user->id)->pluck('user_id')->toArray();
            if(empty($students) || !$user->{$user->role}->course_id){
                $data['works'] = new LengthAwarePaginator([], 0, 25);
                return view('trainer_teacher.works', $data);
            }
            $data['works'] = $query->where('course_id', $user->{$user->role}->course_id)->whereIn('user_id', $students)->latest()->paginate(25);
            return view('trainer_teacher.works', $data);
        }
        $data['works'] = $query->latest()->paginate(25);
        return view('backend.works.index', $data);
    }
    public function changeStatus(Request $request){
        $user = $request->user();
        $request->validate([
            'id' => 'required',
            'status' => 'required|in:approved,declined'
        ]);
        $work = HomeWork::with('course')->findOrFail($request->id);
        DB::transaction(function() use($request, $user, $work){
            if(in_array($user->role, ['teacher', 'trainer'])){
                $work->trainer_status = $request->status;
                $work->save();
                return;
            }
            if($request->status == 'approved'){
                if($work->course?->commission){
                    credit_balance($work->user_id, $work->course?->commission, "Work Submission Bonus from: {$work->course->name}");
                }
            }
            $work->status = $request->status;
            $work->save();
        });

        ToastMagic::success("Status has been updated");
        return redirect()->back();
    }
    public function destroy(Request $request, $id){
        $work = HomeWork::findOrFail($id);
        $work->delete();

        ToastMagic::success("Submiited work has been deleted");
        return redirect()->back();
    }
    public function studentWorks(){
        $data['title'] = "Work Submit";
        $data['courses'] = Course::where('work_submit', true)->latest()->get();
        $data['works'] = HomeWork::with('course:id,name')->where('user_id', Auth::id())->latest()->paginate(25);
        return view('student.work-submit', $data);
    }

    public function storeStudentWorks(Request $request){
        $request->validate([
            'course' => 'required',
            'link' => 'required',
        ]);

        $user = $request->user();

        $settings = config('app.settings');
        $total_limit = $settings['total_work_limit'];
        $today_limit = $settings['per_day_per_course_work_limit'];

        $totalWorks = HomeWork::where([['user_id', $user->id], ['status', 'approved']])->count();
        if($totalWorks >= $total_limit){
            ToastMagic::error("Total submission limit crossed");
            return redirect()->back();
        }

        $dailyLimit = HomeWork::whereDate('created_at', now()->format('Y-m-d'))
        ->where([['user_id', $user->id], ['course_id', $request->course]])->count();
        if($dailyLimit >= $today_limit){
            ToastMagic::error("Selected course daily submission limit crossed");
            return redirect()->back();
        }

        HomeWork::create([
            'user_id' => $user->id,
            'course_id' => $request->course,
            'link' => $request->link,
            'note' => $request->note,
        ]);
        ToastMagic::success("Work has been submitted");
        return redirect()->back();
    }
}