<?php

namespace App\Http\Controllers;

use DB;
use Hash;
use File;
use App\Models\Gender;
use App\Models\Account;
use App\Models\Country;
use App\Models\BloodGroup;
use App\Models\MasterType;
use Illuminate\Support\Arr;
use App\Models\AccountBank;
use App\Models\AccountImage;
use App\Models\StudentHouse;
use Illuminate\Http\Request;
use App\Models\AccountTitle;
use App\Models\MaritalStatus;
use App\Models\CompanyAddress;
use App\Models\AccountLicense;
use App\Models\AccountPayment;
use App\Models\AccountAddress;
use App\Models\AccountContact;
use App\Models\MasterCategory;
use App\Exports\StudentsExport;
use App\Imports\ImportStudent;
use App\Models\LmsClassSection;
use App\Models\AccountingGroup;
use Yajra\DataTables\DataTables;
use App\Models\AccountAttachment;
use Spatie\Permission\Models\Role;
use App\Models\TaxRegisterCategory;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
use App\Models\Designation;

class FacultyController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:faculty-list|faculty-create|faculty-edit|faculty-delete', ['only' => ['index', 'store']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = Account::select([
            'accounts.*',
            'accounting_groups.name as group_name',
            'account_addresses.address_line1 as address',
            'countries.name as country',
            'states.name as state',
            'cities.name as city',
            'account_contacts.phone_no',
            'account_contacts.email',
            'account_contacts.account_gender_id',
            'account_contacts.date_of_birth',
            'genders.name as gender',
            'account_categories.category_name AS category',
        ])
            ->leftjoin('account_contacts','account_contacts.account_id','accounts.id')
            ->leftjoin('accounting_groups','accounting_groups.id','accounts.accounting_group_id')
            ->leftjoin('account_addresses','account_addresses.account_id','accounts.id')
            ->leftjoin('countries', 'countries.id', 'account_addresses.country_id')
            ->leftjoin('states', 'states.id', 'account_addresses.state_id')
            ->leftjoin('cities', 'cities.id', 'account_addresses.city_id')
            ->leftjoin('account_categories', 'account_categories.id', 'accounts.account_category_id')
            ->leftjoin('genders', 'genders.id', 'account_contacts.account_gender_id')
            ->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');
            $search_type = $request->get('search_type');

            $data = $data->where('account_types.type_name', 'like', '%Faculty%')
            ->when(!empty($search_query) && !empty($search_type),
                function ($query) use ($search_query, $search_type) {
                    if ($search_type == 'name') {
                        $query->where('accounts.name', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'code') {
                        $query->where('accounts.code', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'gender') {
                        $query->where('genders.name', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'category') {
                        $query->where('account_categories.category_name', 'like', '%'.$search_query.'%');
                    } else if ($search_type == 'phone') {
                        $query->where('account_contacts.phone_no', 'like', '%'.$search_query.'%');
                    }
                }
            )
            ->orderBy('priority','ASC')
            ->paginate($sort_by);

            return view('faculty.table', compact('data'));
        } else {
            $data = $data->where('account_types.type_name', 'like', '%Faculty%')
                ->orderBy('priority','ASC')
                ->paginate(10);

            return view('faculty.index',compact('data'));
        }
    }

    public function list(Request $request)
    {

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority           = Account::max('priority');
        $priority           = $priority != '' ? $priority : 0;
        $designation        = Designation::select('id','name')->get();
        $genders            = Gender::select(['id','name'])->get();
        $maritalStatus      = MaritalStatus::select(['id','name'])->get();
        $bloodGroup         = BloodGroup::select(['id','group'])->get();
        $account_types      = MasterType::where('account_types.type_name', 'like', '%Faculty%')->get();
        $account_categories = MasterCategory::select(['id','category_name'])->get();
        $accounting_groups  = AccountingGroup::select(['id','name'])->whereNull('deleted_at')->get();
        $account_title      = AccountTitle::select(['id','name','value'])->where('status', '1')->get();
        $country            = Country::select(['id','name'])->where('status', '1')->get();

        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCode     = $country_code->country_code ?? 'us';

        $tax_register_categories = TaxRegisterCategory::select(['id','name'])->whereNull('deleted_at')->get();

        $countryCode = $company_address->country_code ?? 'us';
        $houses = StudentHouse::all();
        $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());

        return view('faculty.create', compact([
            'houses',
            'country',
            'company_address',
            'countryCode',
            'account_types',
            'account_categories',
            'tax_register_categories',
            'genders',
            'maritalStatus',
            'bloodGroup',
            'account_title',
            'accounting_groups',
            'designation',
            'priority',
            'companyDateFormate'
        ]));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = [
            'tax_register_category_id' => 'required',
            'account_type_id'          => 'required',
            'account_category_id'      => 'required',
            // 'accounting_group_id'   => 'required',
            'name'                     => 'required',
        ];

        $type = MasterType::findOrFail($request->account_type_id);

        if (isset($type) && strtolower($type->type_name) != 'faculty') {
            $rules['accounting_group_id'] = 'required';
        // } else {
            // $rules['unique_register_no'] = 'required|unique:accounts,unique_register_no';
        }

        $validator = \Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'country_id',
            'state_id',
            'cityid',
            'city_id',
            'phone_no',
            'whatsapp_no',
            'address_line1',
            'email',
            'contact',
            'date_of_birth',
            'account_gender_id',
            'blood_group_id',
            'marital_status',
            'qualifications',
            'any_known_allergies',
            'pin'
        ]);

        $data['company_id'] = auth()->user()->company_id;
        $account = Account::create($data);

        if (isset($type) && strtolower($type->type_code) == 'general') {
            $accounting_groups = AccountingGroup::find($request->accounting_group_id);
            $count  = 1;
            $prefix = "AC";
            if($accounting_groups) {
                $count  = $accounting_groups->count != '' ? $accounting_groups->count + 1 : 1;
                $prefix = $accounting_groups->prefix != '' ? $accounting_groups->prefix : "AC";

                $accounting_groups->update(['count' => $count]);
            }

            $enquiry_id = $this->generateCode($count, $prefix);

            $account->update(['code' => $enquiry_id]);
        }else {
            $count  = 1;
            $prefix = "AC";

            if($type) {
                $count  = $type->count != '' ? $type->count + 1 : 1;
                $prefix = $type->prefix != '' ? $type->prefix : "AC";

                $type->update(['count' => $count]);
            }

            $enquiry_id = $this->generateCode($count, $prefix);

            $account->update(['code' => $enquiry_id]);
        }

        $address = AccountAddress::insert([
            'account_id'    => $account->id,
            'country_id'    => $request->country_id,
            'state_id'      => $request->state_id,
            'city_id'       => $request->city_id,
            'address_line1' => $request->address_line1,
            'is_default'    => '1',
            'post_code'     => $request->pin
        ]);

        $contact = AccountContact::insert([
            'account_id'          => $account->id,
            'phone_no'            => $request->phone_no,
            'whatsapp_no'         => $request->whatsapp_no,
            'email'               => $request->email ?? '',
            'name'                => $request->contact ?? '',
            'date_of_birth'       => $request->date_of_birth != '' ? date('Y-m-d', strtotime($request->date_of_birth)) : null,
            'account_gender_id'   => $request->account_gender_id ?? '',
            'blood_group_id'      => $request->blood_group_id ?? '',
            'marital_status'      => $request->marital_status ?? '',
            'any_known_allergies' => $request->any_known_allergies ?? '',
            'country_id'          => $request->country_id,
            'state_id'            => $request->state_id,
            'city_id'             => $request->city_id,
            'qualifications'      => $request->qualifications,
        ]);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Faculty has been created successfully',
            ]);
        }
        return redirect()->back()
            ->with('success','Faculty has been created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $account = Account::select([
            'accounts.*',
            'account_types.type_name',
            'account_categories.category_name',
            'accounting_groups.name as group_name',
            'account_images.image',
            'countries.name as country',
            'states.name as state',
            'cities.name as city',
            'account_contacts.date_of_birth',
            'marital_statuses.name as marital_status',
            'genders.name as gender',
            'blood_groups.group as blood_group',
            'account_contacts.guardian_name',
            'account_contacts.anniversary_date',
            'account_contacts.any_known_allergies',
        ])
            ->leftjoin('account_types','account_types.id','accounts.account_type_id')
            ->leftjoin('account_categories','account_categories.id','accounts.account_category_id')
            ->leftjoin('accounting_groups','accounting_groups.id','accounts.accounting_group_id')
            ->leftjoin('account_images','account_images.account_id','accounts.id')
            ->leftjoin('account_contacts','account_contacts.account_id','accounts.id')
            ->leftjoin('marital_statuses', 'marital_statuses.id', 'account_contacts.marital_status')
            ->leftjoin('countries', 'countries.id', 'account_contacts.country_id')
            ->leftjoin('states', 'states.id', 'account_contacts.state_id')
            ->leftjoin('cities', 'cities.id', 'account_contacts.city_id')
            ->leftjoin('genders', 'genders.id', 'account_contacts.account_gender_id')
            ->leftjoin('blood_groups', 'blood_groups.id', 'account_contacts.blood_group_id')
            ->where('accounts.id', $id)->first();


        return view('faculty.show', compact('account'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $genders                 = Gender::select(['id','name'])->get();
        $maritalStatus           = MaritalStatus::select(['id','name'])->get();
        $bloodGroup              = BloodGroup::select(['id','group'])->get();
        $account_title           = AccountTitle::select(['id','name','value'])->where('status', '1')->get();

        $account                 = Account::with('first_account_address','account_contact')->where('id',$id)->first();

        $account_types           = MasterType::select(['id','type_name'])->get();
        $account_categories      = MasterCategory::select(['id','category_name'])->get();
        $accounting_groups       = AccountingGroup::select(['id','name'])->whereNull('deleted_at')->get();
        $tax_register_categories = TaxRegisterCategory::select(['id','name'])->whereNull('deleted_at')->get();
        $houses                  = StudentHouse::all();
        $country                 = Country::select(['id','name'])->where('status', '1')->get();

        $company_address = \Session::get('company_data')['companies_addresses'];
        $countryCode     = $country_code->country_code ?? 'us';
        $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());

        return view('faculty.edit', compact([
            'houses',
            'account',
            'account_types',
            'account_categories',
            'tax_register_categories',
            'accounting_groups',
            //
            'country',
            'company_address',
            'countryCode',
            'genders',
            'maritalStatus',
            'bloodGroup',
            'account_title',
            'companyDateFormate'
        ]));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $rules = [
            // 'accounting_group_id' => 'required',
            'name'                => 'required',
        ];

        $acc  = Account::findOrFail($id);
        $type = MasterType::findOrFail($acc->account_type_id);

        if (isset($type) && strtolower($type->type_name) != 'faculty') {
            $rules['accounting_group_id'] = 'required';
        } else {
            // $rules['unique_register_no'] = 'required|unique:accounts,unique_register_no,'.$id;
        }

        $validator = \Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'country_id',
            'state_id',
            'cityid',
            'city_id',
            'phone_no',
            'whatsapp_no',
            'address_line1',
            'email',
            'contact',
            'date_of_birth',
            'account_gender_id',
            'blood_group_id',
            'marital_status',
            'any_known_allergies',
            'qualifications',
        ]);

        $account = Account::find($id);

        if (!$account) {
            return redirect()->route('faculty.index')
                ->with('error','Faculty not found!');
        }

        $data['company_id'] = auth()->user()->company_id;
        $account->update($data);

        $address = AccountAddress::updateOrCreate([
            'account_id'    => $id
        ],[
            'country_id'    => $request->country_id,
            'state_id'      => $request->state_id,
            'city_id'       => $request->city_id,
            'address_line1' => $request->address_line1,
            'is_default'    => '1'
        ]);

        $contact = AccountContact::updateOrCreate([
            'account_id'    => $id
        ],[
            'phone_no'            => $request->phone_no,
            'whatsapp_no'         => $request->whatsapp_no,
            'email'               => $request->email ?? '',
            'name'                => $request->contact ?? '',
            'date_of_birth'       => $request->date_of_birth != '' ? date('Y-m-d', strtotime($request->date_of_birth)) : '',
            'account_gender_id'   => $request->account_gender_id ?? '',
            'blood_group_id'      => $request->blood_group_id ?? '',
            'marital_status'      => $request->marital_status ?? '',
            'any_known_allergies' => $request->any_known_allergies ?? '',
            'country_id'          => $request->country_id,
            'state_id'            => $request->state_id,
            'city_id'             => $request->city_id,
            'qualifications'      => $request->qualifications,
        ]);


        return redirect()->route('faculty.index')
            ->with('success','Faculty has been updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $account = Account::find($request->id);

        // Find and delete all images of this account
        $account_images = AccountImage::select('image','id')->where('account_id', $request->id)->get();

        foreach($account_images as $value) {
            deleteImage($value->image);

            AccountImage::where('id', $value->id)->delete();
        }

        // Find and delete all attachments of this account
        $account_attachment = AccountAttachment::select('file_name','id')->where('account_id', $request->id)->get();

        foreach($account_attachment as $value) {
            deleteImage($value->file_name);

            AccountAttachment::where('id', $value->id)->delete();
        }

        // Find and delete all Licenses
        AccountLicense::where('account_id', $request->id)->delete();

        // Find and delete all Banks
        AccountBank::where('account_id', $request->id)->delete();

        // Find and delete all Contacts
        AccountContact::where('account_id', $request->id)->delete();

        // Find and delete all Addresses
        AccountAddress::where('account_id', $request->id)->delete();

        // Find and delete all Payments
        AccountPayment::where('account_id', $request->id)->delete();

        $account = $account->delete();

        $Redirect = 'accounts';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }


    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status);
            $Update = StudentHouse::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['House status successfully change'],
                    'data' => [
                        'redirect' => '/student-house/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function export(Request $request)
    {
        return Excel::download(new StudentsExport(request()), 'students.xlsx');
    }

    public function import()
    {
        return view('faculty.import');
    }

    public function importStore(Request $request)
    {
        $extension = File::extension($request->file->getClientOriginalName());
        $extension = strtolower($extension);

        if ($extension == 'xlsx' || $extension == 'csv') {
            $file   = $request->file('file')->getRealPath();
            $data = Excel::toArray(new ImportStudent, $request->file('file'));

            if (isset($data[0])) {
                $data = $data[0];
                unset($data[0]);
            }

            $collection = [];

            foreach ($data as $key => $record) {
                if ($record[0] == '' && $record[1] == '' && $record[2] == '' && $record[3] == '' && $record[4] == '' && $record[5] == '' && $record[6] == '' && $record[7] == '' && $record[8] == '' && $record[9] == '' && $record[10] == '') {
                    continue;
                }

                if ($record[0] == '') {
                    $message = 'Admission no is required.';

                    return redirect()->back()
                        ->with('error', $message);
                } elseif ($record[1] == '') {
                    $message = 'Name is required.';

                    return redirect()->back()
                        ->with('error', $message);
                } elseif ($record[2] == '') {
                    $message = 'Gender is required.';

                    return redirect()->back()
                        ->with('error', $message);
                } elseif ($record[3] == '') {
                    $message = 'Marital Status is required.';

                    return redirect()->back()
                        ->with('error', $message);
                } elseif ($record[4] == '') {
                    $message = 'Date Of Birth is required.';

                    return redirect()->back()
                        ->with('error', $message);
                } elseif ($record[5] == '') {
                    $message = 'Category is required.';

                    return redirect()->back()
                        ->with('error', $message);
                } elseif ($record[6] == '') {
                    $message = 'Phone No. is required.';

                    return redirect()->back()
                        ->with('error', $message);
                } elseif ($record[7] == '') {
                    $message = 'Email is required.';
                } elseif ($record[8] == '') {
                    $message = 'Blood Group is required.';

                    return redirect()->back()
                        ->with('error', $message);
                } elseif ($record[9] == '') {
                    $message = 'Address is required.';

                    return redirect()->back()
                        ->with('error', $message);
                } elseif ($record[10] == '') {
                    $message = 'House is required.';

                    return redirect()->back()
                        ->with('error', $message);
                }

                $gender          = $record[2];
                $bloodGroup      = $record[8];
                $maritalStatus   = $record[3];
                $bloodGroupId    = BloodGroup::whereGroup($bloodGroup)->first();
                $genderId        = Gender::whereName($gender)->first();
                $maritalStatusId = MaritalStatus::whereName($maritalStatus)->first();
                $studentType      = MasterType::where('type_name', 'LIKE', '%Student%')
                    ->first();

                if (isset($bloodGroupId) && !empty($bloodGroupId)) {
                    $bloodGroupId = $bloodGroupId->id;
                } else {
                    return redirect()->back()->with('error', 'Blood group is invalid, please type valid value!');
                }

                if (isset($genderId) && !empty($genderId)) {
                    $genderId = $genderId->id;
                } else {
                    return redirect()->back()->with('error', 'Gender is invalid, please type valid value!');
                }

                if (isset($maritalStatusId) && !empty($maritalStatusId)) {
                    $maritalStatusId = $maritalStatusId->id;
                } else {
                    return redirect()->back()->with('error', 'Marital Status is invalid, please type valid value!');
                }

                // $collection[] = $record;

                // Store data.
                $find = Account::where('unique_register_no', $record[0])->exists();

                if (!$find) {
                    $account = Account::create([
                        'unique_register_no'  => $record[0],
                        'name'                => $record[1],
                        'print_name'          => $record[1],
                        'account_category_id' => $record[5],
                        'account_type_id'     => $studentType->id,
                        'house_group_id'      => $record[10]
                    ]);

                    $address = AccountAddress::insert([
                        'account_id'    => $account->id,
                        'country_id'    => '',
                        'state_id'      => '',
                        'city_id'       => '',
                        'address_line1' => $record[9],
                        'is_default'    => '1'
                    ]);

                    $contact = AccountContact::insert([
                        'account_id'          => $account->id,
                        'phone_no'            => $record[6],
                        'whatsapp_no'         => '',
                        'email'               => $record[7],
                        'name'                => $record[1],
                        'date_of_birth'       => $record[4] != '' ? date('Y-m-d', strtotime($record[4])) : '',
                        'account_gender_id'   => $genderId,
                        'blood_group_id'      => $bloodGroupId,
                        'marital_status'      => $maritalStatusId,
                        'any_known_allergies' => '',
                        'country_id'          => '',
                        'state_id'            => '',
                        'city_id'             => '',
                    ]);
                } else {
                    $account = Account::where('unique_register_no', $record[0])->update([
                        'unique_register_no'  => $record[0],
                        'name'                => $record[1],
                        'print_name'          => $record[1],
                        'account_category_id' => $record[5],
                        'account_type_id'     => $studentType->id,
                        'house_group_id'      => $record[10]
                    ]);
                }
            }

            return redirect()->route('students.index')
                ->with('success', 'Students are imported successfully.');
        } else {
            return redirect()->back()
                ->with('error', 'Please upload valid Excel file format.');
        }
    }
}
