<?php
namespace App\Http\Controllers\API\Invoices;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Response;
use App\Http\Resources\User\UserResource;
use Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Log;
use Carbon\Carbon;
/**
 * Class DemoController
 * @package App\Http\Controllers\API
 */

class BaseInvoiceController extends AppBaseController
{

    protected function handleDBException($exception){
        Log::error($exception);
        return $this->sendValidationError($exception->getMessage());
    }

    public function deleteInvoice($invoiceId){
        $invoice = \App\Models\Invoice::find($invoiceId);   
        $invoice->delete();
        return $this->sendResponseMessage('Invoice deleted succesfully');
    }


    public function amount($input, $item){
        if(isset($input[$item])){
            return $input[$item];
        }
        return 0;
    }
    public function viewInvoice($invoiceId){
        $invoice = \App\Models\Invoice::find($invoiceId); 
        return $this->sendDataResponse(new \App\Http\Resources\Invoice\InvoiceResource($invoice));
    }

    public function listInvoice(Request $request){
        $query = $request->get('query');
        $type = $request->get('type');
        $invoices =null;

        $user = Auth::user();
        if ($user->hasPermission('limitlist.invoices')) { // you can pass an id or slug
            $consumptions = \App\Models\Invoice::orderBy('created_at','DESC')->where('created_by',$user->id)->take(config('app_data.limit_list_count'))->get();
            return  new \App\Http\Resources\LimitlistPaginationResourceCollection($consumptions, \App\Http\Resources\Invoice\InvoiceResource::class);      
        }else{
            if(!empty($type) && !empty($query)){
                $ids = \App\Models\Account::where('name','LIKE', '%'.$query.'%')->pluck('id')->toArray();
                $invoices = \App\Models\Invoice::where('invoice_type','=', $type)->where(function ($query) use ($ids){
                    $query->whereIn('account_id', $ids);
                })->orderBy('invoice_date','DESC')->paginate(config('app_data.per_page_data'));    
            }elseif(!empty($query)){
                $ids = \App\Models\Account::where('name','LIKE', '%'.$query.'%')->pluck('id')->toArray();
                $invoices = \App\Models\Invoice::whereIn('account_id', $ids)->orderBy('invoice_date','DESC')->paginate(config('app_data.per_page_data'));
            }else if(!empty($type)){
                $invoices = \App\Models\Invoice::where('invoice_type','=', $type)->orderBy('invoice_date', 'DESC')->paginate(config('app_data.per_page_data'));
            }else{
                $invoices = \App\Models\Invoice::orderBy('invoice_date', 'DESC')->paginate(config('app_data.per_page_data'));
            }
        }



        
        
        return  new \App\Http\Resources\BasePaginationResourceCollection($invoices, collect($invoices->items()), \App\Http\Resources\Invoice\InvoiceResource::class);
    }

    public function formatDate($date){
        Log::info('formatDate '.$date);
        return Carbon::createFromFormat('d-m-Y', $date)->format('Y-m-d');
    }

    public function invoiceFullRules(){
        return [ 
            'invoice_date' => 'required|date|date_format:d-m-Y',
            'invoice_final_date' => 'nullable|date|date_format:d-m-Y',
            'account_id' => 'required|integer|exists:accounts,id',
            'cgst' => 'nullable|numeric',
            'sgst' => 'nullable|numeric',
            'discount_val' => 'nullable|numeric',
            'discount' => 'nullable|numeric',
            'transport' => 'nullable|numeric',
            'taxable_amount' => 'nullable|numeric',
            'billedAmount' => 'nullable|numeric',
            'totalAmount' => 'required|numeric'
        ]; 
    }
    public function validateFullInvoiceRequest($invoiceRules, Request $request){
        
        $input = $request->all();
        $array = json_decode($input['data'], true);

        $validator = Validator::make($input, $invoiceRules);
          //dd($input['data']);
  
         // $request->validate($rules);
          if ($validator->fails()) 
           { 
             throw new \Illuminate\Validation\ValidationException($validator);
             //throw $error;
           }
    }



    

}

