<?php

namespace App\Http\Controllers;

use App\Models\ClassRoom;
use App\Models\Evaluation;
use App\Models\Exam;
use App\Models\StudentSubscribe;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use \Mpdf\Mpdf as PDF;

class ReportController extends Controller
{
    public $subscriberIds;

    public function classRoom()
    {
        return "class Room";
    }
    public $is_present;
    public $is_absent;
    public function attendances()
    {
        try {
            // اسمالدورة التدريبية $room->name;
            // عدد الدروس $room->lessonsCount;
            // عدد الطلاب $room->studentsCount;
            // نسبة الحضور $presentsAll;
            // نسبة الغياب  $absentsAll;
            $presentsAll = 0;
            $absentsAll = 0;
            $rooms = ClassRoom::get()->map(function ($item) {
                $presents = 0;
                $absents = 0;

                // count lessons for each room
                $item->lessonsCount = $item->course->lessons->count();

                // count students for each room
                $item->studentsCount = $item->students->count();

                // foreach fro count present students in every attendance for each room
                foreach ($item->students as $key => $student) {
                    $presents += $student->attendances
                        ->map(function ($item) {
                            if ($item->is_present == 1) {
                                return $item;
                            }

                        })->reject(function ($item) {
                        return empty($item);
                    })->count();
                }

                // foreach fro count absent students in every attendance for each room
                foreach ($item->students as $key => $student) {
                    $absents += $student->attendances
                        ->map(function ($item) {
                            if ($item->is_present == -1) {
                                return $item;
                            }

                        })->reject(function ($item) {
                        return empty($item);
                    })->count();
                }
                // put attendance values in room
                $item->presentsCount = $presents;
                $item->absentsCount = $absents;
                if ($item->course->lessons->count() * $item->students->count() > 0) {

                    $item->presentsPercentage = $presents / ($item->course->lessons->count() * $item->students->count()) * 100;
                    $item->absentsPercentage = $absents / ($item->course->lessons->count() * $item->students->count()) * 100;
                    $item->notAttendantPercentage = 100 - ($item->presentsPercentage + $item->absentsPercentage);
                }
                return $item;
            });
            return view('reports.attendances')->with('rooms', $rooms);
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لا توجد بيانات   ']);
        }
    }
    /**
     * [Description for exam]
     *
     * @return [type]
     *
     */
    public function exam()
    {
        try {
            $rooms = ClassRoom::get()->map(function ($item) {
                // count lessons for each room
                $item->lessonsCount = $item->course->lessons->count();

                // count students for each room
                $item->studentsCount = $item->students->count();
                return $item;
            });
            return view('reports.exams-rooms')->with('rooms', $rooms);
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لا توجد بيانات   ']);
        }
    }
    /**
     * [Description for studentExam]
     *
     * @param mixed $roomId
     *
     * @return [type]
     *
     */
    public function studentExam($roomId)
    {
        try {
            $exams = Exam::with('uploaded')->where('room_id', $roomId)->get();
            if ($exams->count() > 0) {

                $exams->map(function ($item) {
                    $item->uploaded->map(function ($item) {
                        foreach ($item->answers as $answer) {
                            $item->totalMark += $answer->mark;
                            $item->questionMark += $answer->question->mark;
                        }
                        return $item->answers;
                    });
                    return $item;
                });
            } else {
                return back()->with(['error' => 'لا توجد بيانات']);
            }
            return view('reports.exam-room')->with('exams', $exams);
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لا توجد بيانات   ']);
        }
    }

    /**
     * searching value in array
     *
     * @param mixed $value
     * @param mixed $array
     *
     * @return bool
     *
     */
    public function arraySearch($value, $array)
    {
        foreach ($array as $item) {
            if ($value == $item) {
                return true;
            }

        }
        return false;
    }

    /**
     * [Description for evaluationData]
     *
     * @param mixed $roomId
     *
     * @return [type]
     *
     */
    public function evaluationData($roomId)
    {
        try {
            $room = ClassRoom::find($roomId);
            $this->subscriberIds = StudentSubscribe::where('room_id', $roomId)->get()->map(function ($item) {
                return $item->id;
            })->toArray();

            $evaluations = Evaluation::get()->map(function ($item) {
                if ($item->type == 0) {
                    $item->values->map(function ($item) {
                        foreach ($item->uploads as $key => $upload) {
                            if ($this->arraySearch($upload->subscribe_id, $this->subscriberIds)) {
                                // $item->check .= array_search($upload->subscribe_id, $this->subscriberIds).'-';
                                switch ($upload->value) {
                                    case '4':
                                        $item->excellent++;
                                        $item->count++;
                                        break;
                                    case '3':
                                        $item->very_good++;
                                        $item->count++;
                                        break;
                                    case '2':
                                        $item->good++;
                                        $item->count++;
                                        break;
                                    case '1':
                                        $item->week++;
                                        $item->count++;
                                        break;
                                    default:
                                        break;
                                }
                            }
                            // array_
                        }
                        if ($item->count > 0) {
                            (int) $item->excellent = $item->excellent / $item->count * 100;
                            (int) $item->very_good = $item->very_good / $item->count * 100;
                            (int) $item->good = $item->good / $item->count * 100;
                            (int) $item->week = $item->week / $item->count * 100;
                        }
                    });
                } else {
                    $item->is_text = 1;
                }

                return $item;
            });

            return [
                'room'=> $room,
                'evaluations' => $evaluations,
            ];
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لا توجد بيانات   ']);
        }
    }

    /**
     * [Description for studentAttendanceData]
     *
     * @param mixed $roomId
     *
     * @return [type]
     *
     */
    public function studentAttendanceData($roomId)
    {
        try {
            $presentsAll = 0;
            $absentsAll = 0;
            $notAttendantAll = 0;
            $rooms = StudentSubscribe::where('room_id', $roomId)->get()->map(function ($item) {
                $presents = 0;
                $absents = 0;

                // count lessons for each room
                $item->lessonsCount = $item->room->course->lessons->count();

                // foreach fro count present students in every attendance for each room
                $presents += $item->attendances
                    ->map(function ($item) {
                        if ($item->is_present == 1) {
                            return $item;
                        }

                    })->reject(function ($item) {
                    return empty($item);
                })->count();

                // foreach fro count absent students in every attendance for each room
                $absents += $item->attendances
                    ->map(function ($item) {
                        if ($item->is_present == -1) {
                            return $item;
                        }

                    })->reject(function ($item) {
                    return empty($item);
                })->count();

                // put attendance values in room
                $item->presentsCount = $presents;
                $item->absentsCount = $absents;
                if ($item->lessonsCount > 0) {

                    $item->presentsPercentage = $presents / ($item->lessonsCount) * 100;
                    $item->absentsPercentage = $absents / ($item->lessonsCount) * 100;
                    $item->notAttendantPercentage = 100 - ($item->presentsPercentage + $item->absentsPercentage);
                }
                return $item;
            });
            $arrayDays = [
                'Sun' => 'الأحد',
                'Mon' => 'الإثنين',
                'Tue' => 'الثلاثاء',
                'Wed' => 'الأربعاء',
                'Thu' => 'الخميس',
                'Fri' => 'الجمعة',
                'Sat' => 'السبت',
            ];

            foreach ($rooms as $key => $room) {
                $presentsAll += $room->presentsPercentage;
                $absentsAll += $room->absentsPercentage;
                $notAttendantAll += $room->notAttendantPercentage;
            }
            $presentsAll = $presentsAll / $rooms->count();
            $absentsAll = $absentsAll / $rooms->count();
            $notAttendantAll = $notAttendantAll / $rooms->count();

            $presentsAllDeg = 360 * ($presentsAll) / 100;
            $absentsAllDeg = 360 * ($absentsAll) / 100;
            $notAttendantAllDeg = 360 * ($notAttendantAll) / 100;

            return [
                'rooms' => $rooms,
                'presentsAll' => $presentsAll,
                'absentsAll' => $absentsAll,
                'notAttendantAll' => $notAttendantAll,
                'presentsAllDeg' => $presentsAllDeg,
                'absentsAllDeg' => $absentsAllDeg,
                'notAttendantAllDeg' => $notAttendantAllDeg,
                'arrayDays' => $arrayDays,
            ];
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لا توجد بيانات   ']);
        }
    }

    public function trainerAttendances()
    {
        try {
            // اسمالدورة التدريبية $room->name;
            // عدد الدروس $room->lessonsCount;
            // عدد الطلاب $room->studentsCount;
            // نسبة الحضور $presentsAll;
            // نسبة الغياب  $absentsAll;
            $presentsAll = 0;
            $absentsAll = 0;
            $rooms = ClassRoom::where('trainer_id',Auth::id())->get()->map(function ($item) {
                $presents = 0;
                $absents = 0;

                // count lessons for each room
                $item->lessonsCount = $item->course->lessons->count();

                // count students for each room
                $item->studentsCount = $item->students->count();

                // foreach fro count present students in every attendance for each room
                foreach ($item->students as $key => $student) {
                    $presents += $student->attendances
                        ->map(function ($item) {
                            if ($item->is_present == 1) {
                                return $item;
                            }

                        })->reject(function ($item) {
                        return empty($item);
                    })->count();
                }

                // foreach fro count absent students in every attendance for each room
                foreach ($item->students as $key => $student) {
                    $absents += $student->attendances
                        ->map(function ($item) {
                            if ($item->is_present == -1) {
                                return $item;
                            }

                        })->reject(function ($item) {
                        return empty($item);
                    })->count();
                }
                // put attendance values in room
                $item->presentsCount = $presents;
                $item->absentsCount = $absents;
                if ($item->course->lessons->count() * $item->students->count() > 0) {

                    $item->presentsPercentage = $presents / ($item->course->lessons->count() * $item->students->count()) * 100;
                    $item->absentsPercentage = $absents / ($item->course->lessons->count() * $item->students->count()) * 100;
                    $item->notAttendantPercentage = 100 - ($item->presentsPercentage + $item->absentsPercentage);
                }
                return $item;
            });
            return view('reports.attendances')->with('rooms', $rooms);
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لا توجد بيانات   ']);
        }
    }
    /**
     * [Description for exam]
     *
     * @return [type]
     *
     */
    public function trainerExam()
    {
        try {
            $rooms = ClassRoom::where('trainer_id',Auth::id())->get()->map(function ($item) {
                // count lessons for each room
                $item->lessonsCount = $item->course->lessons->count();

                // count students for each room
                $item->studentsCount = $item->students->count();
                return $item;
            });
            return view('reports.exams-rooms')->with('rooms', $rooms);
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لا توجد بيانات   ']);
        }
    }
    /**
     * [Description for evaluation]
     *
     * @param mixed $roomId
     *
     * @return [type]
     *
     */
    public function evaluationStudent($roomId)
    {
        try {
            return view('reports.evaluation')->with($this->evaluationData($roomId));
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لا توجد بيانات   ']);
        }
    }

    /**
     * [Description for evaluation]
     *
     * @return [type]
     *
     */
    public function evaluation()
    {
        try {
            $rooms = ClassRoom::get()->map(function ($item) {
                // count lessons for each room
                $item->lessonsCount = $item->course->lessons->count();
                // count students for each room
                $item->studentsCount = $item->students->count();
                return $item;
            });
            return view('reports.evaluation-room')->with('rooms', $rooms);
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لا توجد بيانات   ']);
        }
    }
    /**
     * [Description for studentAttendance]
     *
     * @param mixed $roomId
     *
     * @return [type]
     *
     */
    public function studentAttendance($roomId)
    {
        try {
            return view('reports.attendances-room')->with($this->studentAttendanceData($roomId));
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لا توجد بيانات   ']);
        }
    }
    /**
     * [Description for all]
     *
     * @param mixed $roomId
     *
     * @return [type]
     *
     */
    public function all($roomId)
    {
        $exams = ['exams' => Exam::with('uploaded')
                ->where('room_id', $roomId)->get()
                ->map(function ($item) {
                    $item->uploaded->map(function ($item) {
                        foreach ($item->answers as $answer) {
                            $item->totalMark += $answer->mark;
                            $item->questionMark += $answer->question->mark;
                        }
                        return $item->answers;
                    });

                    return $item;
                })];
        $all = array_merge($this->studentAttendanceData($roomId), $this->evaluationData($roomId), $exams);
        // Setup a filename

        return view('reports.all')->with($all);
    }

    public function allReport()
    {
        try {
            $rooms = ClassRoom::get()->map(function ($item) {
                // count lessons for each room
                $item->lessonsCount = $item->course->lessons->count();
                // count students for each room
                $item->studentsCount = $item->students->count();
                return $item;
            });
            return view('reports.all-room-report')->with('rooms', $rooms);
        } catch (\Throwable$th) {
            return back()->with(['error' => 'لا توجد بيانات   ']);
        }
    }
    
    public function pdf()
    {
        $documentFileName = "fun.pdf";

        // Create the mPDF document
        $document = new PDF([
            'mode' => 'utf-8',
            'format' => 'A4',
            'margin_header' => '3',
            'margin_top' => '20',
            'margin_bottom' => '20',
            'margin_footer' => '2',
            'autoArabic' => true,
            'default_font' => 'Amiri', 'serif', 'XB Riyaz',
        ]);

        // Set some header informations for output
        $header = [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'inline; filename="' . $documentFileName . '"',
        ];
        $document->SetDirectionality('rtl');
        //  $document->SetAutoFont();
        // Write some simple Content
        $document->WriteHTML('<h1 style="color:blue">TheCodingJack</h1>');
        $document->WriteHTML('<p>Write something, just for fun!</p>');

        // Use Blade if you want
        //$document->WriteHTML(view('fun.testtemplate'));
        $document->WriteHTML(view('reports.all')->with($all));
        // Save PDF on your public storage
        Storage::disk('public')->put($documentFileName, $document->Output($documentFileName, "S"));

        // Get file back from storage with the give header informations
        return Storage::disk('public')->download($documentFileName, 'Request', $header); //

    }
}
