<?php

namespace App\Http\Controllers\Library;

use App\Http\Controllers\Controller;
use App\Models\BookDetails;
use App\Models\FinancialYear;
use App\Models\Language;
use App\Models\Library\BookBulkUploadTemp;
use App\Models\Library\OpeningStock;
use App\Models\LibrarySetting\BookClass;
use App\Models\LibrarySetting\BookFormates;
use App\Models\LibrarySetting\LibrarianAuthors;
use App\Models\LibrarySetting\LibrarianGernes;
use App\Models\LibrarySetting\LibrarianPublishers;
use App\Models\LibrarySetting\LibrarianTags;
use App\Models\LibrarySetting\Stream;
use App\Models\LibrarySetting\Translators;
use App\Models\Product;
use App\Models\ProductImages;
use App\Models\ProductLocation;
use App\Models\ProductLocationRack;
use Database\Seeders\ProductRacksTableSeeder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class BooksOpenApiController extends Controller
{

  public function openApi()
  {
    $totalTempBook=BookBulkUploadTemp::count();
    return view('library.open-api.create',compact('totalTempBook'));
  }
  public function bulkstore(Request $request)
  {
    $validator =  Validator::make($request->all(), [
      'isbn_no' => 'required',
    ]);

    if ($validator->fails()) {
      return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
    } else {
      foreach ($request->isbn_no as $key => $list) {
        $BookBulkdata = BookBulkUploadTemp::where('isbn_no', $request->isbn_no[$key])->first();
        if (empty($BookBulkdata) && $request->book_title[$key] !='') {
          $datas = [
            'isbn_no'         =>  $request->isbn_no[$key],
            'user_id'         =>  Auth::user()->id,
            'book_title'      =>  $request->book_title[$key],
            'authors'         =>  $request->author[$key],
            'publishers'      =>  $request->publisher[$key],
            'pages'           =>  $request->no_of_pages[$key],
            'book_formate'    =>  $request->physical_format[$key],
            'released_date'   =>  $request->publish_date[$key],
            'publish_date'    =>  $request->publish_date[$key],
            'small_cover'     =>  $request->small_cover[$key],
            'medium_cover'    =>  $request->medium_cover[$key],
            'large_cover'     =>  $request->large_cover[$key],
            'edition'         =>  $request->edition_name[$key],
            'mrp'             =>  $request->mrp[$key]??'',
            'qnt'             =>  $request->qty[$key],
          ];
          BookBulkUploadTemp::create($datas);
        }
      }

      $Redirect = '/book-bulk-list';
      return response()->json([
        'success' => true,
        'message' => ['Bulk Upload Store successfully'],
        'data' => [
          'redirect' => $Redirect,
        ]
      ]);
    }
  }

  public function bulklist(Request $request)
  {
    $bookTemDatas = BookBulkUploadTemp::select(['id', 'isbn_no', 'book_title', 'authors', 'qnt', 'publishers', 'pages', 'book_formate', 'status','message'])->where(['user_id' => Auth::user()->id]);
    $sort_by    = $request->get('sortby') ?? 10;
    $sort_type  = $request->get('sorttype');
    $query      = $request->get('query');
    if (!empty($query) && !empty($sort_by) && $query != " ") {
      $bookTemDatas->where('book_title', 'like', '%' . $query . '%');
    }
    $bookTemData = $bookTemDatas->orderBy('id', 'desc')->paginate($sort_by);

    if ($request->ajax()) {
      return view('library.open-api.table', compact('bookTemData'));
    }
    return view('library.open-api.list', compact('bookTemData'));
  }
  public function bulktobook(Request $request)
  {
    $financialYears = FinancialYear::select('financialyearid')->latest('financialyearid')->where('status', '1')->first();
    if(empty($financialYears))
    {
      return response()->json([
        'success' => false,
        'message' => ['Financial Year is Not Generated'],
        'data' => [
          'redirect' => '',
        ]
      ]);
    }
    
    $msg = $msg1 = $msg2 = $msg3 = $msg4 = $msg5 = $msg6 = $msg7 = $msg8='';

    foreach ($request->bulk_id as $key => $list) {
      $BookBulkData      = BookBulkUploadTemp::find($list);
      $isbn_no           = $BookBulkData->isbn_no;
      $book_title        = $BookBulkData->book_title;
      $authors           = $BookBulkData->authors;
      $publishers        = $BookBulkData->publishers;
      $pages             = $BookBulkData->pages;
      $book_formate      = $BookBulkData->book_formate;
      $publish_date      = $BookBulkData->publish_date;
      $edition           = $BookBulkData->edition;
      $small_cover       = $BookBulkData->small_cover ?? '';
      $about_book        = $BookBulkData->about_book;

      $catgory_genres    = $BookBulkData->catgory_genres;
      $stream            = $BookBulkData->stream;
      $translator        = $BookBulkData->translator;
      $laguages          = $BookBulkData->laguages;
      $book_class        = $BookBulkData->book_class;
      $book_tag          = $BookBulkData->book_tag;
      $book_url          = $BookBulkData->book_url;
      $dimensions        = $BookBulkData->dimensions;
      $racks             = $BookBulkData->racks;

      /********************* Small Cover Image****************/
      if ($small_cover) {
         $small_image  = '';
       // $small_image  = getImagesStore($isbn_no, 'small_cover', $small_cover) ?? '';
      } else {
        $small_image  = '';
      }
      $medium_cover   = $BookBulkData->medium_cover ?? '';
      /********************* Medium Cover Image****************/
      if ($medium_cover) {
        //$medium_image   = getImagesStore($isbn_no, 'medium_cover', $medium_cover) ?? '';
         $medium_image   = '';
      } else {
        $medium_image   = '';
      }
      $large_cover      = $BookBulkData->large_cover ?? '';
      /********************* large Cover Image****************/
      if ($large_cover) {
        //$large_image    = getImagesStore($isbn_no, 'large_cover', $large_cover) ?? '';
         $large_image    = '';
      } else {
        $large_image    = '';
      }
      /************************Get Author Data ************************/

      $author_id     =  $authors ? getAuthor($authors) : '';
      if ($author_id) {
        $statusauthor = 2;
        $status = 2;
      } else {
        $statusauthor = 0;
        $status = 0;
        $msg1="Author Name is not valid";
      }

      /************************Get Publisher Data ************************/
      $publisher_id  = $publishers ? getPublisher($publishers) : '';
      if ($publisher_id) {
        $statuspublisher = 2;
        $status = 2;
      } else {
        $statuspublisher = 0;
        $status = 0;
        $msg2="Publisher Name is not valid";
      }

      /************************Get Book Formate Data ************************/
      $book_formate_id  = $book_formate ? getBookFormate($book_formate) : '';
      if ($book_formate_id) {
        $statusformate = 2;
        $status = 2;
      } else {
        $statusformate = 0;
        $status = 0;
        $msg3="Formate Name is not valid";
      }

      /************************Get Book Category Data ************************/
      $book_category_id  = $catgory_genres ? getBookcategory($catgory_genres) : '';
      if ($book_category_id) {
        $statuscategory = 2;
        $status = 2;
      } else {
        $statuscategory = 0;
        $status = 0;
        $msg4="Category Name is not valid";
      }
      // dd($book_category_id);die;

      /************************Get Book Steam Data ************************/
      $book_stream_id  = $stream ? getBookSteam($stream) : '';
      if ($book_stream_id) {
        $statusstream = 2;
        $status = 2;
      } else {
        $statusstream = 0;
        $status = 0;
        $msg5="Stream Name is not valid";
      }


      /************************Get Book Translator Data ************************/
      $book_trasnlator_id  = $translator ? getBookTranslator($translator) : '';
      if ($book_trasnlator_id) {
        $statustranslator = 2;
        $status = 2;
      } else {
        $statustranslator = 0;
        $status = 0;
        $msg6="Translator Name is not valid";
      }

      /************************Get Book Language Data ************************/
      $book_language_id  = $laguages ? getBooklanguage($laguages) : '';
      if ($book_language_id) {
        $statuslanguage = 2;
        $status = 2;
      } else {
        $statuslanguage = 0;
        $status = 0;
        $msg7="Language Name is not valid";
      }

      /************************Get Book Tag Data ************************/
      $book_tag_id  = $book_tag ? getBookTag($book_tag) : '';
      if ($book_tag_id) {
        $statustag = 2;
        $status = 2;
      } else {
        $statustag = 0;
        $status = 0;
        $msg9="Tag Name is not valid";
      }

      /***********************Book Insert Data ********************************/
      // if (
      //   $statusauthor == 2 && $statustag == 2 && $statuslanguage == 2 &&
      //   $statustranslator == 2 && $statusstream == 2 && $statuscategory == 2 &&
      //   $statusformate == 2 && $statuspublisher == 2
      // ) {
        $dataBookData = Product::where(['shortcode' => $isbn_no])->first();
        //dd($dataBookData);die;
        if (empty($dataBookData)) {
          $dataBook = [
            'shortcode'           =>  $isbn_no,
            'short_name'          =>  $book_title,
            'name'                =>  $book_title,
            'category_id'         =>  $book_category_id??'',
            'is_book'             =>  1,
            'item_min_stock_qty'  =>  $request->qnt[$key] ? $request->qnt[$key] : '',
            'company_id'          =>  Auth::user()->company_id ?? 0,
          ];
          $books = Product::create($dataBook);
          $book_id = $books->id;
          if (isset($small_image)) {
            ProductImages::create([
              'product_id' => $book_id,
              'image_type' => 'cover',
              'image_url' => $small_image
            ]);
          }

          $dataBookItems = [
            'book_id'             =>  $book_id,
            'book_format_id'      =>  $book_formate_id ? $book_formate_id : '',
            'edition'             =>  $edition ? $edition : '',
            'print_year'          =>  $publish_date ? date('Y', strtotime($publish_date)) : '',
            'released_date'       =>  $publish_date ? date('Y-m-d', strtotime($publish_date)) : '',
            'no_of_pages'         =>  $pages ? $pages : '',

            'publisher_id'        =>  $publisher_id,
            'author_id'           =>  $author_id,
            'stream_id'           =>  $book_stream_id,
            'translator_id'       =>  $book_trasnlator_id,
            'laguages_id'         =>  $book_language_id,
            'book_tag_id'         =>  $book_tag_id,
            'book_url'            =>  $book_url,
            'dimensions'          =>  $dimensions,
            'price'               =>  $BookBulkData->mrp??'',
          ];
          $bookDetails = BookDetails::create($dataBookItems);

          OpeningStock::create([
            'product_id'          =>  $book_id,
            'main_qty'            =>  $request->qnt[$key] ?? 1,
            'company_id'          =>  Auth::user()->company_id ?? 0,
            'financial_year_id'   => $financialYears->financialyearid,
          ]);

          /************************** Product Rack Location Create and Store *****************/
          $ProductRack  = ProductLocationRack::where('name',$this->generateStringFormate($racks))->first();
          if($ProductRack)
          {
            $rackId = $ProductRack->id;
          }
          else
          {
            if($racks!='')
            {
              $ProductRack  = ProductLocationRack::create([
                'name'          =>  $this->generateStringFormate($racks),
                'warehouse_id'  => 1,
                'company_id'    => Auth::user()->company_id ?? 0,
              ]);
              $rackId = $ProductRack->id;
            }
            else
            {
              $rackId = 0;
            }
          }
          ProductLocation::create([
              'product_id'        => $book_id,
              'company_id'        => Auth::user()->company_id ?? 0,
              'location_rack_id'  => $rackId??0,
          ]);
        }

        $BookBulkData->update(['status' => 2]);
      // } 
      // else {
      //   $msg = $msg1.','.$msg2.','.$msg3.','.$msg4.','.$msg5.','.$msg6.','.$msg7.','.$msg8;
      //   $BookBulkData->update(['status' => 0,'message'=>$msg]);
      // }
    }

    BookBulkUploadTemp::where('status', 2)->delete();

    $Redirect = '/book-bulk-list';

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




  public function bulkstoreajax(Request $request)
  {
    $validator =  Validator::make($request->all(), [
      'isbn_no'     => 'required',
      'book_title'  => 'required',
    ]);
    if ($validator->fails()) {
      return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
    } else {
      foreach ($request->isbn_no as $key => $list) {
        $BookBulkdata = BookBulkUploadTemp::where('isbn_no', $request->isbn_no[$key])->first();
        if (empty($BookBulkdata)) {
          $datas = [
            'isbn_no'         =>  $request->isbn_no[$key],
            'user_id'         =>  Auth::user()->id,
            'book_title'      =>  $request->book_title[$key],
            'authors'         =>  $request->author[$key],
            'publishers'      =>  $request->publisher[$key],
            'pages'           =>  $request->no_of_pages[$key],
            'book_formate'    =>  $request->physical_format[$key],
            'released_date'   =>  $request->publish_date[$key],
            'publish_date'    =>  $request->publish_date[$key],
            'small_cover'     =>  $request->small_cover[$key],
            'medium_cover'    =>  $request->medium_cover[$key],
            'large_cover'     =>  $request->large_cover[$key],
            'edition'         =>  $request->edition_name[$key],
            'mrp'             =>  $request->mrp[$key]??'',
            'qnt'             =>  $request->qty[$key],
          ];
          BookBulkUploadTemp::create($datas);
        } else {
          $datas = [
            'isbn_no'         =>  $request->isbn_no[$key],
            'user_id'         =>  Auth::user()->id,
            'book_title'      =>  $request->book_title[$key],
            'authors'         =>  $request->author[$key],
            'publishers'      =>  $request->publisher[$key],
            'pages'           =>  $request->no_of_pages[$key],
            'book_formate'    =>  $request->physical_format[$key],
            'released_date'   =>  $request->publish_date[$key],
            'publish_date'    =>  $request->publish_date[$key]??'',
            'small_cover'     =>  $request->small_cover[$key],
            'medium_cover'    =>  $request->medium_cover[$key],
            'large_cover'     =>  $request->large_cover[$key],
            'edition'         =>  $request->edition_name[$key],
            'mrp'             =>  $request->mrp[$key]??'',
            'qnt'             =>  $request->qty[$key],
          ];
          $BookBulkdata->update($datas);
        }
      }

      $Redirect = '/book-bulk-list';
      return response()->json([
        'success' => true,
        'message' => ['Bulk Upload Store successfully'],
        'data' => [
          'redirect' => $Redirect,
        ]
      ]);
    }
  }


  public function deleteBookTempItem(Request $request)
  {
    $bookItem = BookBulkUploadTemp::find($request->id);
    $bookItem->delete();
    $Redirect = '';
    return response()->json([
      'success' => true,
      'message' => ['Deleted successfully'],
      'data' => [
        'redirect' => $Redirect,
        'reload' => true,
      ]
    ]);
  }


  /*************************Book Search With Open Libary Api  ***********************/
  public function bookssearchopenapi(Request $request)
  {
    $query = $request->get('q');
    /************************check aleary exist or not over data base******************/
    $checked = $this->checkbookAvaible($query);
    // dd($checked);
    if ($checked) {
      $data['title']                =     $checked->book_title ?? '';
      $data['isbn_13']              =     $checked->isbn_no ?? '';
      $data['authors']              =     $checked->first_name ?? '';
      $data['publishers']           =     $checked->name ?? '';
      $data['number_of_pages']      =     $checked->no_of_pages ?? '';
      $data['physical_format']      =     $checked->formate_name ?? '';
      $data['publish_date']         =     $checked->released_date ?? '';
      $data['small_cover']          =     '';
      $data['medium_cover']         =     '';
      $data['large_cover']          =     '';
      $data['edition_name']         =     $checked->edition ?? '';
      $data['id']                   =     $checked->id ?? '';
      $data['status']               =     '1';
      $jsonArray = [$data];
    } else {
      $response_body = openApigetDta($query);
      $data = [];

      if ($response_body) {
        foreach ($response_body['records'] as $subArray) {

          $keyToCheck = "cover";
          if (is_array($subArray) && in_array($keyToCheck, array_keys($subArray))) {
            $small_cover      = $subArray['data']['cover']['small'];
          } else {
            $small_cover      = '';
          }

          if (isset($subArray['data']['cover']['medium']) && $subArray['data']['cover']['medium'] != '') {
            $medium_cover     = $subArray['data']['cover']['medium'];
          } else {
            $medium_cover     = '';
          }

          if (isset($subArray['data']['cover']['large']) && $subArray['data']['cover']['large'] != '') {
            $large_cover    = $subArray['data']['cover']['large'];
          } else {
            $large_cover    = '';
          }

          if (isset($subArray['details']['details']['edition_name']) && $subArray['details']['details']['edition_name'] != '') {
            $edition_name   = $subArray['details']['details']['edition_name'];
          } else {
            $edition_name = '';
          }

          $data['title']            =     $subArray['details']['details']['title'] ?? '';
          $data['isbn_13']          =     $subArray['details']['bib_key'] ?? '';
          $data['authors']          =     $subArray['details']['details']['authors'][0]['name'] ?? '';
          $data['publishers']       =     $subArray['details']['details']['publishers'][0] ?? '';
          $data['number_of_pages']  =     $subArray['details']['details']['number_of_pages'] ?? '';
          $data['physical_format']  =     $subArray['details']['details']['physical_format'] ?? '';
          $data['publish_date']     =     $subArray['details']['details']['publish_date'] ?? '';
          $data['small_cover']      =     $subArray['data']['cover']['small'] ?? '';
          $data['medium_cover']     =     $subArray['data']['cover']['medium'] ?? '';
          $data['large_cover']      =     $subArray['data']['cover']['large'] ?? '';
          $data['edition_name']     =     $subArray['details']['details']['edition_name'] ?? '';
          $data['status']           =     '1';
          $data['id']               =     '';
        }
        $jsonArray = [$data];
      } else {
        $data['status'] = '0';
        $jsonArray = [$data];
      }
    }


    return response()->json($jsonArray);
  }



  public function checkbookAvaible($isbn_no)
  {
    $books = Product::select(
      [
        'products.id',
        'products.shortcode as isbn_no',
        'products.short_name as book_title',
        'librarian_authors.first_name',
        'librarian_publishers.name',
        'book_details.no_of_pages',
        'book_details.released_date',
        'librarian_book_formates.formate_name',
        'book_details.edition',
      ]
    )
      ->leftJoin('book_details', 'book_details.book_id', '=', 'products.id')
      ->leftJoin('librarian_authors', 'librarian_authors.id', '=', 'book_details.author_id')
      ->leftJoin('librarian_publishers', 'librarian_publishers.id', '=', 'book_details.publisher_id')
      ->leftJoin('librarian_book_formates', 'librarian_book_formates.id', '=', 'book_details.book_format_id')
      ->where('is_book', 1)
      ->where(['products.shortcode' => $isbn_no])
      ->first();
    return $books;
  }

  public function edit($id, Request $request)
  {
    $data = BookBulkUploadTemp::find($request->id);
    return view('library.open-api.edit', compact('data'));
  }
  public function update($id, Request $request)
  {
    $validator =  Validator::make($request->all(), [
      'book_title'      => 'required',
      'qnt'             => 'required',
    ]);
    if ($validator->fails()) {
      return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
    } else {
      $bookData = BookBulkUploadTemp::find($id);
      $bookData->isbn_no             = $request->isbn_no;
      $bookData->user_id             = Auth::user()->id;
      $bookData->book_title          = $this->generateStringFormate($request->book_title);
      $bookData->catgory_genres      = $this->generateStringFormate($request->catgory_genres);
      $bookData->authors             = $this->generateStringFormate($request->authors);
      $bookData->stream              = $this->generateStringFormate($request->stream);
      $bookData->translator          = $this->generateStringFormate($request->translator);
      $bookData->publishers          = $this->generateStringFormate($request->publishers);
      $bookData->laguages            = $this->generateStringFormate($request->laguages);
      $bookData->pages               = $request->pages;
      $bookData->book_class          = $this->generateStringFormate($request->book_class);
      $bookData->book_tag            = $this->generateStringFormate($request->book_tag);
      $bookData->book_url            = $request->book_url;
      $bookData->about_book          = $this->generateStringFormate($request->about_book);
      $bookData->qnt                 = $request->qnt;
      $bookData->sale_price          = $request->sale_price;
      $bookData->mrp                 = $request->mrp;
      $bookData->book_formate        = $this->generateStringFormate($request->book_formate);
      $bookData->released_date       = $request->released_date?date('Y-m-d', strtotime($request->released_date)):'';
      $bookData->edition             = $this->generateStringFormate($request->edition);
      $bookData->racks               = $this->generateStringFormate($request->racks);
      $bookData->update();
    }

    $Redirect = '/book-bulk-list';
    return response()->json([
      'success' => true,
      'message' => ['Bulk Upload Store successfully'],
      'data' => [
        'redirect' => $Redirect,
      ]
    ]);
  }
  public function check_error(Request $request)
  {
    if (isset($request->catgory_genres)) {
      $category = LibrarianGernes::where('name', trim($request->catgory_genres))->first();
      if ($category) {
        return response()->json([
          'success' => true,
          'message' => ['This is Avaible'],
        ]);
      } else {
        return response()->json([
          'success' => false,
          'message' => ['This Category is Not Avaible'],
        ]);
      }
    } elseif (isset($request->authors)) {
      $authors = LibrarianAuthors::where('first_name', trim($request->authors))->first();
      if ($authors) {
        return response()->json([
          'success' => true,
          'message' => ['This is Avaible'],
        ]);
      } else {
        return response()->json([
          'success' => false,
          'message' => ['This Author is Not Avaible'],
        ]);
      }
    } elseif (isset($request->publishers)) {
      $publishers = LibrarianPublishers::where('name', trim($request->publishers))->first();
      if ($publishers) {
        return response()->json([
          'success' => true,
          'message' => ['This is Avaible'],
        ]);
      } else {
        return response()->json([
          'success' => false,
          'message' => ['This Publisher is Not Avaible'],
        ]);
      }
    } elseif (isset($request->laguages)) {
      $laguages = Language::where('name', trim($request->laguages))->first();
      if ($laguages) {
        return response()->json([
          'success' => true,
          'message' => ['This is Avaible'],
        ]);
      } else {
        return response()->json([
          'success' => false,
          'message' => ['This Language is Not Avaible'],
        ]);
      }
    } elseif (isset($request->stream)) {
      $stream = Stream::where('stream_name', trim($request->stream))->first();
      if ($stream) {
        return response()->json([
          'success' => true,
          'message' => ['This is Avaible'],
        ]);
      } else {
        return response()->json([
          'success' => false,
          'message' => ['This Stream is Not Avaible'],
        ]);
      }
    } elseif (isset($request->book_class)) {
      $book_class = BookClass::where('class_name', trim($request->book_class))->first();
      if ($book_class) {
        return response()->json([
          'success' => true,
          'message' => ['This is Avaible'],
        ]);
      } else {
        return response()->json([
          'success' => false,
          'message' => ['This Class is Not Avaible'],
        ]);
      }
    } elseif (isset($request->book_tag)) {
      $book_tag = LibrarianTags::where('tag_name', trim($request->book_tag))->first();
      if ($book_tag) {
        return response()->json([
          'success' => true,
          'message' => ['This is Avaible'],
        ]);
      } else {
        return response()->json([
          'success' => false,
          'message' => ['This Tag is Not Avaible'],
        ]);
      }
    } elseif (isset($request->translator)) {
      $translator = Translators::where('translator_name', trim($request->translator))->first();
      if ($translator) {
        return response()->json([
          'success' => true,
          'message' => ['This is Avaible'],
        ]);
      } else {
        return response()->json([
          'success' => false,
          'message' => ['This Translator is Not Avaible'],
        ]);
      }
    } elseif (isset($request->book_formate)) {
      $book_formate = BookFormates::where('formate_name', trim($request->book_formate))->first();
      if ($book_formate) {
        return response()->json([
          'success' => true,
          'message' => ['This is Avaible'],
        ]);
      } else {
        return response()->json([
          'success' => false,
          'message' => ['This Formate is Not Avaible'],
        ]);
      }
    }
  }
}
