<?php

namespace App\Http\Controllers\Library;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\FinancialYear;
use App\Models\Academics\Classes;
use App\Models\Account;
use App\Models\Students\Student;
use App\Models\Students\StudentAdmission;
use App\Models\Library\LibraryCard;
use App\Models\LibrarySetting\CardType;
use App\Models\LibrarySetting\MembershipPlan;
use App\Models\LmsClasses;
use App\Models\StudentAdmission as ModelsStudentAdmission;
use App\Models\VoucherMaster;
use App\Models\VoucherType;
use DB;
use PDF;
use Picqer;

class LibraryCardController extends Controller
{
    public function index(Request $request)
    {
        $libraryCards = LibraryCard::with(['getStudentDetails', 'getClassName', 'getSectionName'])
            ->select(['id', 'account_id', 'admission_id', 'card_no', 'class_id', 
            'section_id', 'date_of_issue', 'valid_upto', 'card_status'])
            ->latest('id');
        $sort_by    = $request->get('sortby') ?? 10;
        $sort_type  = $request->get('sorttype');
        $query      = $request->get('query');

        if (!empty($query) && !empty($sort_by) && $query != " ") {
            $libraryCards->where('admission_id', 'like', '%' . $query . '%')
                ->orWhere('card_no', 'like', '%' . $query . '%');
        }

        $libraryCard = $libraryCards->paginate($sort_by);
        if ($request->ajax()) {
            return view('library.cards.table', compact('libraryCard'));
        } else {
            return view('library.cards.index', compact('libraryCard'));
        }
    }
    public function create()
    {
        $data['academic'] = FinancialYear::select(['financialyearid', 'financial_year_name'])->latest('financialyearid')->get();
        $data['membershiplan'] = MembershipPlan::select(['id', 'name'])->get();
        $data['classes'] = LmsClasses::select(['id', 'class_name'])->get();
        return view('library.cards.create', $data);
    }
    public function show($id, Request $request)
    {
        $Card = LibraryCard::with(['getStudentDetails', 'getClassName', 'getSectionName'])
            ->select(['id', 'account_id', 'admission_id', 'card_no', 'class_id', 'section_id', 'date_of_issue', 'valid_upto'])
            ->find($id);

        if (count($Card->getStudentDetails->account_images) > 0) {
            $image = $Card->getStudentDetails->account_images[0]->image;
        } else {
            $image = "";
        }
        $data['card_no']                = $Card->card_no ? $Card->card_no : "";
        $data['firstname']              = $Card->getStudentDetails->name ? $Card->getStudentDetails->name : "";
        $data['admission_no']           = $Card->getStudentDetails->unique_register_no ? $Card->getStudentDetails->unique_register_no : "";
        $data['class_name']             = $Card->getClassName->class_name ? $Card->getClassName->class_name : "";
        $data['academics_section_id']   = $Card->getSectionName->academics_section_id ? $Card->getSectionName->academics_section_id : "";
        $data['date_of_issue']          = $Card->date_of_issue ? $Card->date_of_issue : "";
        $data['valid_upto']             = $Card->valid_upto ? $Card->valid_upto : "";
        $data['profile_pic']            = $image;

        $generator = new Picqer\Barcode\BarcodeGeneratorHTML();
        $data['borcode'] = $generator->getBarcode($Card->card_no, $generator::TYPE_CODE_128) ? $generator->getBarcode($Card->card_no, $generator::TYPE_CODE_128) : "";


        return view('library.cards.show', $data);
    }
    public function downloads($id, Request $request)
    {
        $Card = LibraryCard::with(['getStudentDetails', 'getClassName', 'getSectionName'])
            ->select([
                'id', 'account_id', 'admission_id', 'card_no', 'class_id',
                'section_id', 'date_of_issue', 'valid_upto'
            ])
            ->find($id);
        $data['card_no']                = $Card->card_no ? $Card->card_no : "";
        $data['firstname']              = $Card->getStudentDetails->name ? $Card->getStudentDetails->name : "";
        $data['admission_no']           = $Card->getStudentDetails->unique_register_no ? $Card->getStudentDetails->unique_register_no : "";
        $data['class_name']             = $Card->getClassName->class_name ? $Card->getClassName->class_name : "";
        $data['academics_section_id']   = $Card->getSectionName->academics_section_id ? $Card->getSectionName->academics_section_id : "";
        $data['date_of_issue']          = $Card->date_of_issue ? $Card->date_of_issue : "";
        $data['valid_upto']             = $Card->valid_upto ? $Card->valid_upto : "";
        $data['profile_pic']            = $Card->getStudentDetails->account_images[0]->image ? $Card->getStudentDetails->account_images[0]->image : "";

        $generator = new Picqer\Barcode\BarcodeGeneratorHTML();
        $data['borcode'] = $generator->getBarcode($Card->card_no, $generator::TYPE_CODE_128) ? $generator->getBarcode($Card->card_no, $generator::TYPE_CODE_128) : "";
        $pdfs = PDF::loadView('library.cards.demodown', $data);
        $pdfname = "Librarycard";
        return $pdfs->download('' . $pdfname . '.pdf');
    }
    public function GetStudents(Request $request)
    {
        $data = Account::leftJoin('student_admissions', 'accounts.id', '=', 'student_admissions.student_id')
            ->leftJoin('library_cards', 'library_cards.admission_id', '=', 'student_admissions.id')
            ->where('library_cards.admission_id', '=', NULL)
            // ->where(['student_admissions.financial_id'=>$request->financial_id])
            ->where(['student_admissions.class_id' => $request->class_id])
            ->where(['student_admissions.section_id' => $request->section_id])
            ->select(['student_admissions.id', 'accounts.name', 'accounts.unique_register_no'])->get();

        return view('library.cards.cardnotgenerated', compact('data'));
    }
    public function store(Request $request)
    {
        foreach ($request->admission_id as $key => $list) {
            $admissionData = ModelsStudentAdmission::find($list);

            $insert = $this->insertCard($admissionData, $request);
        }
        //return redirect('library/cards')->with('success','License Type created successfully.');
        $Redirect = '/cards/';
        return response()->json([
            'success' => true,
            'message' => ['License Type created successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }
    public function insertCard($admissionData, $request)
    {

        $voucher_master = VoucherMaster::with('voucherSeries')->where('voucher_code', 'LIBRARY_CARD')->first();
        $voucher_type   = VoucherType::with('voucherSeries')->where('code', 'LIBRARY_CARD')->first();

        $library_card_count     = LibraryCard::select('last_card_no_count')->orderBy('created_at', 'DESC')->first();
        $last_card_count        = isset($library_card_count) && isset($library_card_count->last_card_no_count) ? $library_card_count->last_card_no_count + 1 : ($voucher_type->voucherSeries->start_from ?? 1);

        $card_no = $this->generateCode(
            $last_card_count,
            ($voucher_type->voucherSeries->prefix ?? 'MI'),
            ($voucher_type->voucherSeries->postfix ?? ''),
            ($voucher_type->voucherSeries->separator ?? '-'),
            ($voucher_type->voucherSeries->length ?? 5)
        );


        $financialYears = FinancialYear::select(['financialyearid', 'financial_year_end_date'])->latest('financialyearid')->where('status', '1')->first();


        $Cards = LibraryCard::create([
            'account_id'            => $admissionData->student_id,
            'card_type'             => 1,
            'last_card_no_count'    => $last_card_count,
            'financial_id'          => $financialYears->financialyearid,
            'membership_id'         => $request->membership_id,
            'admission_id'          => $admissionData->id,
            'card_no'               => $card_no,
            'class_id'              => $admissionData->class_id,
            'section_id'            => $admissionData->section_id,
            'date_of_issue'         => date('Y-m-d'),
            'valid_upto'            => $financialYears->financial_year_end_date
        ]);
        return $Cards;
    }

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

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