<?php

namespace App\Http\Controllers\Library;

use App\Exports\ExportBookStock;
use App\Http\Controllers\Controller;
use App\Imports\ImportBookOpeningStock;
use App\Models\FinancialYear;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class BookOpeningStockController extends Controller
{
  public function openingStock(Request $request)
  {
    $data['finnancialyearData'] = FinancialYear::select(['financialyearid', 'financial_year_name'])->where('status', '1')->latest('financialyearid')->get();
    return view('library.opening-stock.create', $data);
  }

  public function exportbookstock(Request $request)
  {
    $dataFilter = Product::select(['shortcode as isbn_no', 'short_name as book_title'])->where('is_book', 1)->latest('id')->get();

    return Excel::download(new ExportBookStock($dataFilter->toArray()), 'Book-Stock-list.xlsx');
  }
  public function importbookstock(Request $request)
  {
    $validator =  Validator::make($request->all(), [
      'book_stock' => 'required|mimes:csv,xlsx,xls|max:5000',
    ]);
    if ($validator->fails()) {
      return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
    } else {
      $CompanyData  = getComapnyName();
      $company_id   = $CompanyData->id;
      $financialYears = FinancialYear::select('financialyearid')->latest('financialyearid')->where('status', '1')->first();
      $datas = Excel::import(new ImportBookOpeningStock($company_id, $financialYears->financialyearid), $request->file('book_stock')->store('files'));
      $Redirect = '/books';
      return response()->json([
        'success' => true,
        'message' => ['Book Opening Stock Uploaded Successfully'],
        'data' => [
          'redirect' => $Redirect,
          'reload' => false,
        ]
      ]);
    }
  }
}
