<?php

namespace App\Http\Controllers\Library;

use App\Http\Controllers\Controller;
use App\Models\FinancialYear;
use App\Models\InvoiceSerialSetting;
use App\Models\Librarian\Books;
use App\Models\Library\BookIssue;
use App\Models\Library\BookIssueDetail;
use App\Models\Library\BookReturn;
use App\Models\Library\BookReturnDetail;
use App\Models\Students\Student;
use App\Models\TblStock;
use App\Models\VoucherMaster;
use App\Models\VoucherType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Picqer;

class BookReturnIssueController extends Controller
{
    public function index(Request $request)
    {
        //DB::enableQueryLog();
        $BookReturns = BookReturnDetail::with(['getIssuedetails'])
            ->select(['id', 'book_issue_detail_id', 'product_id', 'return_date', 'return_no', DB::raw('SUM(return_qty) as sumreturn_qty')])
            ->groupBy('return_no');

        $query      = $request->get('query');
        $sort_by    = $request->get('sortby') ?? 10;
        $sort_type  = $request->get('sorttype');
        
        if (!empty($query) && !empty($sort_by) && $query != " ") {
            $BookReturns = $BookReturns->whereRelation('getIssuedetails.getisseuBook.getStudentDetails', 'name', 'like', '%' . $query . '%')
                ->OrWhere('return_no', 'like', '%' . $query . '%');
        }

        $BookReturn = $BookReturns->paginate($sort_by);

        if ($request->ajax()) {
            return view('library.book-return.table', compact('BookReturn'));
        } else {
            return view('library.book-return.index', compact('BookReturn'));
        }
    }

    public function create(Request $request)
    {
        $financialYears = FinancialYear::select(['financialyearid','financial_year_name','is_default'])->where(['status' => '1'])->orderBy('financialyearid','desc')->get();
        return view('library.book-return.create',compact('financialYears'));
    }



    public function returnBooksearch(Request $request)
    {

        $filterResult = BookIssueDetail::leftJoin('book_issues', 'book_issues.id', '=', 'book_issue_details.book_issue_id')
            ->leftJoin('products', 'products.id', '=', 'book_issue_details.product_id')
            ->where(['book_issues.account_id' => $request->student_id, 'return_status' => 'No'])
            ->select(['products.short_name', 'book_issue_details.qnt', 'book_issues.issue_date', 'book_issue_details.id', 'book_issue_details.return_due_date'])->get();
        return view('library.book-return.book-list', compact('filterResult'));
    }

    public function show($id, Request $request)
    {
        $bookReturn = BookReturnDetail::with(['getIssuedetails'])->latest('id')->where('return_no', $id)->get();

        $data['bookReturn'] = $bookReturn;
        $generator = new Picqer\Barcode\BarcodeGeneratorHTML();
        $data['borcode'] = $generator->getBarcode($bookReturn[0]->return_no, $generator::TYPE_CODE_128) ? $generator->getBarcode($bookReturn[0]->return_no, $generator::TYPE_CODE_128) : "";
        return view('library.book-return.show', $data);
    }
    public function print($id, Request $request)
    {
        $bookReturn = BookReturnDetail::with(['getIssuedetails'])->latest('id')->where('return_no', $id)->get();
        $data['bookReturn'] = $bookReturn;
        $generator = new Picqer\Barcode\BarcodeGeneratorHTML();
        $data['borcode'] = $generator->getBarcode($bookReturn[0]->return_no, $generator::TYPE_CODE_128) ? $generator->getBarcode($bookReturn[0]->return_no, $generator::TYPE_CODE_128) : "";
        return view('library.book-return.print', $data);
    }
    public function edit($id, Request $request)
    {

        $data['bookReturn'] = BookReturnDetail::with(['getIssuedetails'])->latest('id')->where('return_no', $id)->get();
        $data['id']        = $id;
        $data['financialYears'] = FinancialYear::select(['financialyearid','financial_year_name','is_default'])->where(['status' => '1'])->orderBy('financialyearid','desc')->get();
        //dd($data['bookReturn']);die;
        return view('library.book-return.edit', $data);
    }

    public function editget(Request $request)
    {
        $data['bookReturn'] = BookReturnDetail::with(['getIssuedetails'])->latest('id')->where('return_no', $request->id)->get();
        // dd($data['bookReturn']);die;
        return view('library.book-return.edit-table', $data);
    }


    

    public function store(Request $request)
    {
        //dd($request);exit;

        $request->validate([
            'book_issue_id' => 'required',
        ]);

        /************************Get Book Return No ******************/
        $voucher_master = VoucherMaster::with('voucherSeries')->where('voucher_code', 'INVENTORY')->first();
        $voucher_type   = VoucherType::with('voucherSeries')->where('code', 'MATERAIL_RETURN')->first();

        $return_count      = BookReturn::select('last_return_no_count')->orderBy('created_at', 'DESC')->first();
        $last_return_count = isset($return_count) && isset($return_count->last_return_no_count) ? $return_count->last_return_no_count + 1 : ($voucher_type->voucherSeries->start_from ?? 1);

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

        $bookReturns    =   BookReturn::create(['return_no'               => $return_no,
                                                'last_return_no_count'    =>    $last_return_count]);
        $book_return_id =   $bookReturns->id;


        foreach ($request->book_issue_id as $key => $list) {
            $BookIssueDeatisl   =   BookIssueDetail::where('id', $list)->first();
            $book_issue         =   $BookIssueDeatisl->book_issue_id;
            $this->addremark($request->remark, $book_issue);
            /*******************************Book Return Tbale Insert  *********************/
            //$book_return_id=$this->book_returninsert($book_issue,$financialYears->financialyearid);

            if (isset($request->book_issue_damage[$key]) && $request->book_issue_damage[$key] == 'on') {
                $damage_status = '1';
            } else {
                $damage_status = '0';
            }
            /*******************************Book Return Details Insert  *********************/
            $this->bookReturn_details($book_return_id, $list, $BookIssueDeatisl->book_id, $return_no, $damage_status, $request->qnt[$key], $request->damageqnt[$key], $request->damage_amount[$key], date('Y-m-d', strtotime($request->return_date)));

            $UpdateBookDetails = [
                'return_status' =>  'Yes',
                'return_date'   =>  date('Y-m-d', strtotime($request->return_date)),
                'qnt'           =>  $request->qnt[$key],
            ];
            $BookIssueDeatisl->update($UpdateBookDetails);

            if (isset($request->book_issue_damage[$key]) && $request->book_issue_damage[$key] == 'on') {
            } else {
                $InsertStock    = [
                    'financial_id'      =>  $request->financial_year_id,
                    'invoice_id'        =>  $book_return_id,
                    'stock_type'        =>  'Book Return',
                    'stock_item_date'   =>  date('Y-m-d'),
                    'stock_item_id'     =>  $BookIssueDeatisl->book_id,
                    'stock_in'          =>  $request->qnt[$key],
                    'stock_company_id'  =>  Auth::user()->company_id,

                ];
                TblStock::create($InsertStock);
            }
            // Book Damage Cart
        }

        return response()->json([
            'success' => true,
            'message' => ['Book Return successfully!'],
            'data' => [
                'redirect' => '/book-return',
            ],
        ]);

        // return redirect('library/book-return')->with('success', 'Book Return successfully');
    }
    public function update($id, Request $request)
    {
        $request->validate([
            'book_issue_id' => 'required',
        ]);

        /************************Get Book Return No ******************/
        $return_no      =   $id;

        $bookReturns    =   BookReturn::where(['return_no' => $return_no])->first();
        $book_return_id =   $bookReturns->id;

        foreach ($request->book_issue_id as $key => $list) {
            $BookIssueDeatisl   =   BookIssueDetail::where('id', $list)->first();
            $book_issue         =   $BookIssueDeatisl->book_issue_id;
            $this->addremark($request->remark, $book_issue);
            /*******************************Book Return Tbale Insert  *********************/
            //$book_return_id=$this->book_returninsert($book_issue,$request->financial_year_id);

            if (isset($request->book_issue_damage[$key]) && $request->book_issue_damage[$key] == 'on') {
                $damage_status = '1';
            } else {
                $damage_status = '0';
            }
            /*******************************Book Return Details Insert  *********************/
            $this->bookReturn_details($book_return_id, $list, $BookIssueDeatisl->product_id, $return_no, $damage_status, $request->qnt[$key], $request->damageqnt[$key], $request->damage_amount[$key], date('Y-m-d', strtotime($request->return_date)));

            $UpdateBookDetails = [
                'return_status' =>  'Yes',
                'return_date'   =>  date('Y-m-d', strtotime($request->return_date)),
            ];
            $BookIssueDeatisl->update($UpdateBookDetails);

            $bookReturnDetails  = BookReturnDetail::where([
                'book_issue_detail_id'      =>  $list,
                'book_return_id'            =>  $book_return_id,
            ])
                ->first();

            if (isset($request->book_issue_damage[$key]) && $request->book_issue_damage[$key] == 'on') {
                TblStock::where([
                    'invoice_id'        =>  $book_return_id,
                    'stock_item_id'     =>  $BookIssueDeatisl->product_id,
                ])->delete();
            } else {
                if (empty($bookReturnDetails)) {
                    $InsertStock    = [
                        'financial_id'      =>  $request->financial_year_id,
                        'invoice_id'        =>  $book_return_id,
                        'stock_type'        =>  'Book Return',
                        'stock_item_date'   =>  date('Y-m-d'),
                        'stock_item_id'     =>  $BookIssueDeatisl->product_id,
                        'stock_in'          =>  $request->qnt[$key],
                        'stock_company_id'  =>  Auth::user()->company_id,
                    ];
                    TblStock::create($InsertStock);
                }
            }
        }
        return response()->json([
            'success' => true,
            'message' => ['Book Return Update successfully'],
            'data' => [
                'redirect' => '/book-return',
            ],
        ]);
        // return redirect('library/book-return')->with('success', 'Book Return Update successfully');
    }

    public function addremark($remark, $book_issue_id)
    {
        $book_issueData = BookIssue::find($book_issue_id);
        if ($book_issueData) {
            $book_issueData->update(['remark' => $remark]);
            return true;
        } else {
            return true;
        }
    }

    public function book_returninsert($book_issue, $financialyearid)
    {
        $bookIssueData = BookIssue::find($book_issue);
        $dataBookReturn = [
            'member_id'     =>  $bookIssueData,
            'financial_id'  =>  $financialyearid,
            'return_no'     =>  rand(1000, 9999),
            'issue_date'    =>  $bookIssueData,
            'return_date'   =>  date('Y-m-d'),
        ];
        $save = BookReturn::create($dataBookReturn);
        return $save->id;
    }
    /***************************Book Return Details Insert ***************/
    public function bookReturn_details($book_return_id, $book_issue_detail_id, $book_id, $return_no, $damage_status, $return_qty, $damage_qty, $damage_amount, $return_date)
    {
        $bookReturnDetails  = BookReturnDetail::where([
            'book_issue_detail_id'      =>  $book_issue_detail_id,
            'book_return_id'            =>  $book_return_id
        ])
            ->first();
        if (!empty($bookReturnDetails)) {
            $UpdateData = [
                'damage_status'            =>  $damage_status,
                'return_qty'               =>  $return_qty,
                'damage_qty'               =>  $damage_qty,
                'amount'                   =>  $damage_amount,
                'return_date'              =>  $return_date,

            ];
            $bookReturnDetails->update($UpdateData);
        } else {
            BookReturnDetail::create([
                'book_issue_detail_id'      =>  $book_issue_detail_id,
                'book_return_id'            =>  $book_return_id,
                'product_id'                =>  $book_id,
                'return_no'                 =>  $return_no,
                'return_date'               =>  $return_date,
                'damage_status'             =>  $damage_status,
                'return_qty'                =>  $return_qty,
                'damage_qty'                =>  $damage_qty,
                'amount'                    =>  $damage_amount
            ]);
        }
    }
    public function deletebookitem(Request $request)
    {
        $BookIssueDetails = BookIssueDetail::where('id', $request->id)->first();
        $UpdateBookDetails = [
            'return_status' => 'No',
            'return_date'   => '',
        ];
        $BookIssueDetails->update($UpdateBookDetails);

        $datas = BookReturnDetail::where('book_issue_detail_id', $request->id)->first();
        //dd(DB::getQueryLog());
        $invoice_id = $datas->book_return_id;

        $book_id = $datas->book_id;

        $datas->delete();

        //dd($invoice_id);die;
        /*********************Book Return Main Table Remove Data *********************/
        BookReturn::where(['id' => $datas->book_return_id])->delete();

        /************************************ Stock Table Remove Stock In Return Book **************/

        //DB::enableQueryLog();
        TblStock::where(['invoice_id' => $invoice_id, 'stock_item_id' => $book_id, 'stock_type' => 'Book Return'])->delete();

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

    public function deletebook(Request $request)
    {
        //DB::enableQueryLog(); 
        $datas = BookReturnDetail::where('id', $request->id)->first();
        //dd(DB::getQueryLog());
        $book_return_id = $datas->book_return_id;
        $book_issue_detail_id = $datas->book_issue_detail_id;

        /*******************Book Return Details Delete ************************/
        BookReturnDetail::where('book_return_id', $book_return_id)->delete();

        /*******************Book Issue Update Details ************************/
        BookIssueDetail::where('id', $book_issue_detail_id)->update(['return_status' => 'No']);

        $bookReturns = BookReturn::where('id', $datas->book_return_id);
        $bookReturns->delete();
        /************************Stock Table Update Stock Delete Return Books ***********************/
        TblStock::where(['invoice_id' => $book_return_id, 'stock_type' => 'Book Return'])->delete();

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


    /*******************Generate Book Return No ********************/
    public function generatebookReturnNo()
    {
        /*********************Book Return Count **********************/
        $getDataSerial = InvoiceSerialSetting::where('module_type', 'Book Return')->first();
        $bookIssueCount = BookReturn::count();
        if ($bookIssueCount > 0) {
            return $bookReturnNo = $getDataSerial->prefix . '00' . $bookIssueCount + 1;
        } else {

            if ($getDataSerial) {
                return $bookReturnNo = $getDataSerial->prefix . '00' . $getDataSerial->startfrom + 1;
            } else {
                return $bookReturnNo = 'BR001';
            }
        }
    }
}
