<?php

namespace App\Http\Controllers;

use DateTime;
use DateInterval;
use DatePeriod;

use PDF;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

use Yajra\DataTables\Facades\DataTables;

use App\Models\Admin;
use App\Models\Attendance;
use App\Models\ClassRoom;
use App\Models\ClassRoomActivity;
use App\Models\Exam;
use App\Models\ExamResult;
use App\Models\Payment;
use App\Models\PresentScheduleRel;
use App\Models\Schedule;
use App\Models\ScheduleSubjectRel;
use App\Models\Student;
use App\Models\Subject;
use App\Models\Teacher;
use App\Models\User;

class AdminController extends Controller
{
  public function Helloworld(Request $request)
  {
    return view('helloworld');
  }

  public function index(Request $request)
  {
    try {
      $admins = Admin::orderBy('id', 'desc')->paginate(10);

      Session::forget('status');

      return view('admins.index', compact('request', 'admins'));
    } catch (\Exception $e) {
      // dd($e);

      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return 'list admins failed';
    }
  }

  public function create(Request $request)
  {
    return view('admins.create', compact('request'));
  }

  public function store(Request $request)
  {
    try {
      $validatedData = $request->validate([
        'firstName' => 'required',
        'lastName' => 'required',
        'dateOfBirth' => 'required',
        'gender' => '',
        'email' => 'required',
        'contact' => '',
        'skills' => '',
        'password' => 'required',
      ]);

      DB::beginTransaction();

      $user = new User();
      $user->name = join(', ', [
        $validatedData['firstName'],
        $validatedData['lastName'],
      ]);
      $user->email = $validatedData['email'];
      $user->password = $validatedData['password'];
      $user->role = 'admin';
      $user->save();
      $new_user_id = $user->id;

      $admin = new Admin();
      $admin->firstName = $validatedData['firstName'];
      $admin->lastName = $validatedData['lastName'];
      $admin->dateOfBirth = $validatedData['dateOfBirth'];
      if (isset($validatedData['gender'])) {
        $admin->gender = $validatedData['gender'];
      }
      $admin->email = $validatedData['email'];
      // $admin->subject_id = join(',', $validatedData['subject_id']);

      if (isset($validatedData['contact'])) {
        $admin->contact = $validatedData['contact'];
      }

      if (isset($validatedData['skills'])) {
        $admin->skills = $validatedData['skills'];
      }

      $admin->user_id = $new_user_id;

      if ($request->avatarAction == 'NO_CHANGE') {
        // $teacher->avatar = NULL;
      } elseif ($request->avatarAction == 'CLEAR') {
        // NOTE: user intent clear avatar
        $teacher->avatar = null;
      } elseif ($request->avatarAction == 'UPDATE_AVATAR') {
        // NOTE: user intent change avatar
        $avatarFileName =
          str_replace('@', '_', str_replace('.', '_', $teacher->email)) .
          '.' .
          $request->avatar->getClientOriginalExtension();

        $request->avatar->move(public_path('avatars'), $avatarFileName);

        $teacher->avatar = $avatarFileName;
      }

      $admin->save();

      DB::commit();
      Session::forget('status');

      return redirect()
        ->route('admins.index')
        ->with('success', 'Admin has been created successfully.');
    } catch (\Exception $e) {
      DB::rollback();
      dd($e);

      // TODO: no password should display error status

      $message = $e->getMessage();
      $request->session()->put('status', $message);
      return view('admins.edit', compact('admin', 'request'));
    }
  }

  public function show(Request $request, Admin $admin)
  {
    return view('admins.show', compact('admin', 'request'));
  }

  public function edit(Request $request, Admin $admin)
  {
    return view('admins.edit', compact('request', 'admin'));
  }

  public function update(Request $request, Admin $admin)
  {
    try {
      $validatedData = $request->validate([
        'firstName' => 'required',
        'lastName' => 'required',
        'dateOfBirth' => 'required',
        'gender' => '',
        'email' => 'required',
        'contact' => '',
        'skills' => '',
      ]);

      DB::beginTransaction();

      $admin->fill($request->post())->save();

      if ($request['password']) {
        $user->password = $request['password'];
      }

      if ($request->avatarAction == 'NO_CHANGE') {
      } elseif ($request->avatarAction == 'CLEAR') {
        // NOTE: user intent clear avatar
        $admin->avatar = null;
      } elseif ($request->avatarAction == 'UPDATE_AVATAR') {
        // NOTE: user intent change avatar
        $avatarFileName =
          str_replace('@', '_', str_replace('.', '_', $admin->email)) .
          '.' .
          $request->avatar->getClientOriginalExtension();

        $request->avatar->move(public_path('avatars'), $avatarFileName);

        $admin->avatar = $avatarFileName;
      }

      $admin->save();

      DB::commit();

      return redirect()
        ->route('admins.index')
        ->with('success', 'Admin Has Been updated successfully');
    } catch (\Exception $e) {
      DB::rollback();
      dd($e);

      $message = $e->getMessage();
      $request->session()->put('status', $message);
      return view('admins.edit', compact('admin', 'request'));
    }
  }

  public function destroy(Request $request, Admin $admin)
  {
    try {
      DB::beginTransaction();

      $admin_id = $admin->id;
      $admin = Admin::find($admin_id);

      $user_id = $admin->user_id;
      $user = User::find($user_id);

      $admin->delete();
      if ($user) {
        $user->delete();
      }

      DB::commit();

      return redirect()
        ->route('admins.index')
        ->with('success', 'admin has been deleted successfully');
    } catch (\Exception $e) {
      DB::rollback();
      dd($e);
      return 'delete admin failed';
    }

    return redirect()
      ->route('admins.index')
      ->with('success', 'Admin has been deleted successfully');
  }

  public function showDashboard(Request $request)
  {
    try {
      $email_to_find = $request->user()->email;
      $current_user = Admin::where('email', $email_to_find)->get()[0];

      $num_of_schedule = Schedule::count();
      $num_of_student = Student::count();
      $num_of_teacher = Teacher::count();
      $num_of_exam = 0;
      $num_of_classroom = 0;
      $num_of_subject = 0;

      return view(
        'admins.showDashboard',
        compact(
          'request',
          'num_of_student',
          'num_of_teacher',
          'num_of_classroom',
          'num_of_subject',
          'num_of_schedule',
          'current_user'
        )
      );
    } catch (\Exception $e) {
      return redirect()->route('login');
    }
  }

  public function dtGetAdmins(Request $request)
  {
    $admins = Admin::select(['id', 'firstName', 'lastName', 'gender', 'email']);

    return DataTables::eloquent($admins)->toJson();
  }

  public function showPayments(Request $request)
  {
    try {
      $email_to_find = $request->user()->email;
      // $current_admin = Admin::where('email', $email_to_find)
      //     ->get()[0];

      return view('admins.showPayments', compact('request'));
    } catch (\Exception $e) {
      dd($e);

      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return 'list admins failed';
    }
  }

  public function viewPayments(Request $request, string $payment_id)
  {
    try {
      $email_to_find = $request->user()->email;
      $current_admin = Admin::where('email', $email_to_find)->get()[0];

      $payment = Payment::find($payment_id);

      return view('admins.viewPayments', compact('request', 'payment'));
    } catch (\Exception $e) {
      dd($e);

      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return 'list admins failed';
    }
  }

  public function editPayments(Request $request, string $payment_id)
  {
    try {
      $email_to_find = $request->user()->email;
      $current_admin = Admin::where('email', $email_to_find)->get()[0];

      $payment = Payment::find($payment_id);

      return view(
        'admins.editPayments',
        compact('request', 'payment', 'payment_id')
      );
    } catch (\Exception $e) {
      dd($e);

      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return 'edit admins failed';
    }
  }

  public function storePayment(Request $request)
  {
    try {
      $validatedData = $request->validate([
        'date' => 'required',
        'student_id' => 'required',
        'subject' => 'required',
        'amount' => 'required',
        'remarks' => '',
      ]);

      $email_to_find = $request->user()->email;

      // $current_admin = Admin::where('email', $email_to_find)
      //     ->get()[0];

      DB::beginTransaction();

      $payment = new Payment();
      $payment->date = $validatedData['date'];
      $payment->student_id = $validatedData['student_id'];
      $payment->subject = $validatedData['subject'];
      $payment->amount = $validatedData['amount'];
      $payment->remarks = $validatedData['remarks'];

      $payment->save();

      Session::forget('status');

      DB::commit();

      return redirect()
        ->route('adminShowPayments')
        ->with('success', 'Payment has been created successfully.');
    } catch (\Exception $e) {
      DB::rollback();
      dd($e);

      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return 'list admins failed';
    }
  }

  public function updatePayment(Request $request, string $payment_id)
  {
    try {
      $email_to_find = $request->user()->email;
      $current_admin = Admin::where('email', $email_to_find)->get()[0];

      DB::beginTransaction();

      $validatedData = $request->validate([
        'date' => 'required',
        'student_id' => 'required',
        'subject' => 'required',
        'amount' => 'required',
        'remarks' => '',
      ]);

      $payment = Payment::find($payment_id);
      $payment->date = $validatedData['date'];
      $payment->student_id = $validatedData['student_id'];
      $payment->subject = $validatedData['subject'];
      $payment->amount = $validatedData['amount'];
      $payment->remarks = $validatedData['remarks'];

      $payment->save();

      DB::commit();
      Session::forget('status');

      return view('admins.showPayments', compact('request', 'payment'));
    } catch (\Exception $e) {
      DB::rollback();

      dd($e);

      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return 'list admins failed';
    }
  }

  public function adminDeletePayment(Request $request, string $payment_id)
  {
    try {
      $email_to_find = $request->user()->email;
      $current_admin = Admin::where('email', $email_to_find)->get()[0];

      DB::beginTransaction();

      $payment = Payment::find($payment_id);
      $payment->delete();

      DB::commit();
      Session::forget('status');

      return view('admins.showPayments', compact('request', 'payment'));
    } catch (\Exception $e) {
      DB::rollback();

      dd($e);

      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return 'list admins failed';
    }
  }

  public function createPayment(Request $request)
  {
    try {
      return view('admins.createPayment', compact('request'));
    } catch (\Exception $e) {
      dd($e);

      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return 'create payment failed';
    }
  }

  public function printPayment(Request $request, string $payment_id)
  {
    try {
      $email_to_find = $request->user()->email;
      $current_admin = Admin::where('email', $email_to_find)->get()[0];

      $payment = Payment::find($payment_id);
      $student = Student::where('email', '=', 'student1@school.com')->get()[0];

      // $pdf = PDF::loadHTML('<h1>Test</h1>');
      $pdf = PDF::loadView('invoice', compact('payment', 'student'));

      // $pdf = PDF::loadFile(public_path().'/myfile.html');
      // return Pdf::loadFile(public_path().'/myfile.html')
      // ->save('/path-to/my_stored_file.pdf')
      // ->stream('download.pdf');
      // $pdf = PDF::loadFile(public_path().'/myfile.html');

      return $pdf->stream();

      dd($payment);

      // return view('admins.work_in_progress');
      return 'hello admin controller';
    } catch (\Exception $e) {
      dd($e);

      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return 'list admins failed';
    }
  }
}
