<?php

namespace App\Http\Controllers\Library;

use App\Http\Controllers\Controller;
use App\Models\Account;
use Illuminate\Http\Request;
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\BookRequest;
use App\Models\Library\BookRequestDetail;
use App\Models\Product;
use App\Models\Students\Student;
use App\Models\TblStock;
use App\Models\VoucherMaster;
use App\Models\VoucherType;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class BookRequestController extends Controller
{
    public function index(Request $request)
    {
        $BookRequests = BookRequest::with(['getRequestDetail', 'bookcount', 'getStudents'])
            ->select(['id', 'order_no', 'order_date', 'status', 'student_id'])->latest('id');
        $sort_by        = $request->get('sortby') ?? 10;
        $sort_type      = $request->get('sorttype');
        $query          = $request->get('query');

        if (!empty($query) && !empty($sort_by) && $query != " ") {

            $BookRequests->whereRelation('getStudents', 'firstname', 'like', '%' . $query . '%')
                ->OrWhere('order_no', 'like', '%' . $query . '%');
        }
        $BookRequest = $BookRequests->paginate($sort_by);
        if ($request->ajax()) {
            return view('library.book-request.table', compact('BookRequest'));
        } else {
            return view('library.book-request.index', compact('BookRequest'));
        }
    }
    public function show($id, Request $request)
    {
        $BookRequest = BookRequest::with(['getRequestDetail.getBook', 'bookcount', 'getStudents'])
            ->select(['id', 'order_no', 'order_date', 'status', 'student_id'])
            ->where('id', $id)->first();
        $financialYears = FinancialYear::select('financialyearid')->latest('financialyearid')->where('status', '1')->first();
        return view('library.book-request.show', compact('BookRequest', 'financialYears'));
    }
    public function creates($id, Request $request)
    {
        $BookRequest = BookRequest::with(['getRequestDetail.getBook', 'bookcount', 'getStudents'])
            ->select(['id', 'order_no', 'order_date', 'status', 'student_id'])
            ->where('id', $id)->first();
        $requestBooks = BookRequestDetail::with('getBook')->where('book_reques_id', $id)->get(['book_id', 'qnt', 'book_reques_id']);
       

        Session::forget('requestCart');
        $cart = session()->get('requestCart', []);

        foreach ($requestBooks as $list) {
            $cart[$list->book_id] = [
                "name"                      => $list->getBook->short_name ?? '',
                'isbn'                      => $list->getBook->shortcode ?? '',
                'author'                    => $list->getBook->book_details->author ?? '',
                'publisher'                  => $list->getBook->book_details->publisher ?? '',
                "quantity"                  => $list->qnt,
                'book_request_detail_id'    => $list->book_reques_id
            ];
            session()->put('requestCart', $cart);
        }
        $financialYears = FinancialYear::select(['financialyearid', 'financial_year_name', 'is_default'])->where(['status' => '1'])->orderBy('financialyearid', 'desc')->get();
        return view('library.book-request.create', compact('BookRequest','financialYears'));
    }


    public function addtorequestcart(Request $request)
    {
        $Book = Books::findOrFail($request->book_id);
        $cart = session()->get('requestCart', []);

        if (isset($cart[$request->book_id])) {
            $cart[$request->book_id]['quantity']++;
        } else {
            $cart[$request->book_id] = [
                "name"                      => $Book->book_title,
                "quantity"                  => 1,
                'book_request_detail_id'    => ''
            ];
        }

        session()->put('requestCart', $cart);
        if ($cart) {
            return response()->json([
                'success' => true,
            ]);
        } else {
            return response()->json([
                'success' => false,
            ]);
        }
    }


    public function getcartrequest(Request $request)
    {
        $data = Session::get('requestCart') ?? [];
        return view('library.book-request.request-cart', compact('data'));
    }

    public function removeRequestCart(Request $request)
    {
        $data = Session::get('requestCart') ?? [];
        $id   = $request->id;

        if ($request->id) {
            $cart = session()->get('requestCart');
            if (isset($cart[$request->id])) {
                unset($cart[$request->id]);
                session()->put('requestCart', $cart);
            }
        }

        return response()->json(['success' => true]);
    }


    public function storestatus(Request $request)
    {
        $validator =  Validator::make($request->all(), [
            'status' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
        } else {
            //return $request->all();
            $BookRequestData = BookRequest::find($request->request_id);
            $BookRequestData->update(['status' => $request->status]);
            if ($request->status == 'Accept') {
                $Redirect = '/book-request/create/' . $request->request_id;
                return response()->json([
                    'success' => true,
                    'message' => ['Request successfully updated'],
                    'data' => [
                        'redirect' => $Redirect,
                        'reload' => true,
                    ]
                ]);
            } else {
                foreach ($request->request_detail_id as $detail_id) {
                    $bookDetails = BookRequestDetail::find($detail_id);
                    $bookDetails->update(['status' => 'Cancelled']);
                }
                $Redirect = '/book-request';
                return response()->json([
                    'success' => true,
                    'message' => ['Request successfully updated'],
                    'data' => [
                        'redirect' => $Redirect,
                        'reload' => true,
                    ]
                ]);
            }
        }
    }

    public function store(Request $request)
    {
        $validator =  Validator::make($request->all(), [
            'student_name' => 'required',
            'book_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
        } else {
            $Studentdata = Account::select('id')->where('id', $request->student_name)->first();
            

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

        # last voucher count for main invoice number
        $voucher_count      = BookIssue::select('last_issue_no_count')->orderBy('created_at', 'DESC')->first();
        $last_voucher_count = isset($voucher_count) && isset($voucher_count->last_issue_no_count) ? $voucher_count->last_issue_no_count + 1 : ($voucher_type->voucherSeries->start_from ?? 1);

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

            $return_due_date = bookexpirecalculate($request->student_name, $request->financial_year_id, date('Y-m-d', strtotime($request->issue_date)));
            // getBook Limit
            $BookLimit = bookLimit($request->student_name, $request->financial_year_id);

            $BookIsue = BookIssue::where('account_id', $Studentdata->id)->where('request_id',$request->request_id)->get();
            $totalqty = 0;
            if(count($BookIsue)>0)
            {
                $Redirect = '/book-issue';
                return response()->json([
                    'success' => true,
                    'message' => ['Book issue Create successfully'],
                    'data' => [
                        'redirect' => $Redirect,
                    ]
                ]);
            }
            else
            {
                foreach ($BookIsue as $issue) {
                    $qnts = BookIssueDetail::where('book_issue_id', $issue->id)->where('return_status', 'No')->sum('qnt');
                    $totalqty += $qnts;
                }
                if ($BookLimit >= $totalqty) {
    
                    $InserBookIsseu['account_id']             = $Studentdata->id;
                    $InserBookIsseu['financial_id']           = $request->financial_year_id;
                    $InserBookIsseu['issue_date']             = date('Y-m-d', strtotime($request->issue_date));
                    $InserBookIsseu['issue_no']               = $issue_no;
                    $InserBookIsseu['last_issue_no_count']    = $last_voucher_count;
                    $InserBookIsseu['request_id']             = $request->request_id;
                    $InserBookIsseu['return_due_date']        = $return_due_date;
                    $booksissue = BookIssue::create($InserBookIsseu);
                    $book_issue_id = $booksissue->id;
                    foreach ($request->book_id as $key => $list) {
                        $BookIsue = BookIssue::where('account_id', $Studentdata->id)->get();
                        $totalqty = 0;
                        foreach ($BookIsue as $issue) {
                            $qnts = BookIssueDetail::where('book_issue_id', $issue->id)->where('return_status', 'No')->sum('qnt');
                            $totalqty += $qnts;
                        }
                        // get Request Book Details
                        if ($request->book_request_detail_id[$key] != '') {
                            $BookRequestDetailData = BookRequestDetail::find($request->book_request_detail_id[$key]);
                            if ($BookLimit >= $totalqty) {
                                $books = Product::select('id')->where('id', $list)->first();
                                $InsertBookDetails = [
                                    'book_issue_id'     => $book_issue_id,
                                    'product_id'        => $books->id,
                                    'qnt'               => $request->qnt[$key],
                                    'return_due_date'   => $return_due_date
                                ];
                                $BookIssueDeatisl = BookIssueDetail::create($InsertBookDetails);
                                $InsertStock = [
                                    'financial_id'    => $request->financial_year_id,
                                    'invoice_id'        => $book_issue_id,
                                    'stock_type'        => 'Book Issue',
                                    'stock_item_date'   => date('Y-m-d', strtotime($request->issue_date)),
                                    'stock_item_id'     => $books->id,
                                    'stock_out'         => $request->qnt[$key],
                                    'stock_company_id'  => Auth::user()->company_id,
                                ];
                                TblStock::create($InsertStock);
                                $BookRequestDetailData->update(['status' => 'Accepted']);
                            } else {
                                $BookRequestDetailData->update(['status' => 'Cancelled']);
                            }
                        } else {
                            if ($BookLimit >= $totalqty) {
                                $books = Product::select('id')->where('id', $list)->first();
                                $InsertBookDetails = [
                                    'book_issue_id'     => $book_issue_id,
                                    'product_id'        => $books->id,
                                    'qnt'               => $request->qnt[$key],
                                    'return_due_date'   => $return_due_date
                                ];
                                $BookIssueDeatisl = BookIssueDetail::create($InsertBookDetails);
                                $InsertStock = [
                                    'financial_id'      => $request->financial_year_id,
                                    'invoice_id'        => $book_issue_id,
                                    'stock_type'        => 'Book Issue',
                                    'stock_item_date'   => date('Y-m-d', strtotime($request->issue_date)),
                                    'stock_item_id'     => $books->id,
                                    'stock_out'         => $request->qnt[$key],
                                    'stock_company_id'  => Auth::user()->company_id,
                                ];
                                TblStock::create($InsertStock);
                            }
                        }
    
                        if (isset($cart[$list])) {
                            unset($cart[$list]);
                            session()->put('requestCart', $cart);
                        }
                    }
                    //return redirect('library/book-issue')->with('success','Book issue Create successfully');
                    $Redirect = '/book-issue';
                    return response()->json([
                        'success' => true,
                        'message' => ['Book issue Create successfully'],
                        'data' => [
                            'redirect' => $Redirect,
                        ]
                    ]);
                } else {
                    $BookRequest = BookRequest::find($request->request_id);
                    $BookRequest->update(['status' => 'Cancelled']);
    
                    $BookDetails = BookRequestDetail::where('book_reques_id', $request->request_id);
                    $BookDetails->update(['status' => 'Cancelled']);
                    //return redirect('library/book-issue')->with('error','You Have Already Limited Book Issue'); 
    
                    $Redirect = '/book-issue';
                    return response()->json([
                        'success' => false,
                        'message' => ['You Have Already Limited Book Issue'],
                        'data' => [
                            'redirect' => $Redirect,
                        ]
                    ]);
                }
            }
           
        }
    }

    public function delete(Request $request)
    {
        $BookIssue = BookRequest::find($request->id);
        $BookIssue->update(['status' => 'Cancel']);


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