<?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;
use App\Repositories\QualityCheckRepository;
/**
 * Class DemoController
 * @package App\Http\Controllers\API
 */

class ConsumableInvoiceController extends BaseInvoiceController
{


    public function validateConsumableDetail($array){
        $rules = [
            '*.consumable_id' => 'required|distinct|exists:consumable_items,id',
            '*.qty' => 'required|numeric',
            '*.unit_price' => 'required|numeric',
            '*.amount' => 'required|numeric'
        ];   
        
        $validator = Validator::make($array, $rules);
        //dd($input['data']);

       // $request->validate($rules);
        if ($validator->fails()) 
         { 
           throw new \Illuminate\Validation\ValidationException($validator);
           //throw $error;
         }

    }


    public function createInvoice(Request $request){
        $invoiceRules = $this->invoiceFullRules();
        $invoiceRules['invoice_type'] = 'required';
        $this->validateFullInvoiceRequest( $invoiceRules, $request);
        $input = $request->all();
        $array = json_decode($input['data'], true);
        $this->validateConsumableDetail($array);

        $success = false;

        $fullInput = $request->all();
            unset($fullInput['data']);
            $fullInput['created_at'] = \Carbon\Carbon::now();
            $fullInput['created_by'] = \Auth::user()->id;
            $fullInput['invoice_date'] = $this->formatDate($input['invoice_date']);

        DB::beginTransaction();
        try {
            
            //$date = Carbon::createFromFormat('d-m-Y g:i a', $input['invoice_date'])->format('Y-m-d');
            $invoiceNumber = \App\Models\Invoice::generateInvoiceNumber($input['invoice_date']);
            $fullInput['invoice_number'] = $invoiceNumber;
            $invoiceId = DB::table('invoices')->insertGetId($fullInput); 
            foreach( $array as $item){
                DB::table('invoice_consumable_detail')->insert([
                    'invoice_id' => $invoiceId,
                    'consumable_id' => $item['consumable_id'],
                    'unit_price' => $item['unit_price'],
                    'qty' => $item['qty'],
                    'amount' => $item['amount'],
                    'created_at' => \Carbon\Carbon::now(),
                    'created_by' => \Auth::user()->id,
                    'cgst' => $this->amount($item, 'cgst'),
                    'sgst' => $this->amount($item, 'sgst'),
                    'igst' => $this->amount($item, 'igst'),
                    'cgst_value' => $this->amount($item, 'cgst_value'),
                    'sgst_value' => $this->amount($item, 'sgst_value'),
                    'igst_value' => $this->amount($item, 'igst_value'),
                    'net_amount' => $this->amount($item, 'net_amount'),
                    'discount' => $this->amount($item, 'discount'),
                    'discount_val' => $this->amount($item, 'discount_val'),
                    'net_gst' => $this->amount($item, 'net_gst'),
                ]); 
            }

            $invoice = \App\Models\Invoice::find($invoiceId);
            Log::info('invoice date entries '.$invoice->invoice_date);
            $entryId = DB::table('entries')->insertGetId([
                'entrytype_id' => 5,
                'ref_number' => $invoice->invoice_number,
                'invoice_ref_id' => $invoice->id,
                'tr_date' => $fullInput['invoice_date'],
                'dr_total' => 0,
                'cr_total' => $input['totalAmount'],
                'created_at' => \Carbon\Carbon::now(),
                'created_by' => \Auth::user()->id,
            ]);


            DB::table('entryitems')->insertGetId([
                'entry_id' => $entryId,
                'account_id' => $invoice->account_id,
                'dr_total' => 0,
                'cr_total' => $input['totalAmount'],
                'created_at' => \Carbon\Carbon::now()
            ]);
            
            DB::commit();
            $invoice = \App\Models\Invoice::find($invoiceId);

            return  $this->sendResponse( new \App\Http\Resources\Invoice\InvoiceResource($invoice), 'Consumable Invoice created successfully.');
            $success = true;
        } catch (\Exception $e) {
            DB::rollback();
            return $this->handleDBException($e);
        } catch (\Throwable $e) {
            DB::rollback();
            return $this->handleDBException($e);
        }   
    }   
    
    
    public function updateInvoice($invoiceId, Request $request){
        $invoice = \App\Models\Invoice::find($invoiceId);   
        
        $invoiceRules = $this->invoiceFullRules();
        $invoiceRules['invoice_type'] = 'required';
        $invoiceRules['invoice_number'] ='required|unique:invoices,invoice_number,'.$invoiceId; 
        //$invoiceRules['invoice_number'] = 'required|exists:invoices,id,'.$invoiceId;
        $this->validateFullInvoiceRequest($invoiceRules, $request);
        $input = $request->all();
        $array = json_decode($input['data'], true);
        $this->validateConsumableDetail($array);

        $success = false;

        $fullInput = $request->all();
            unset($fullInput['data']);
            //$fullInput['invoice_type'] = 'CONSUMABLE';
            $fullInput['updated_at'] = \Carbon\Carbon::now();
            $fullInput['updated_by'] = \Auth::user()->id;
            $fullInput['invoice_date'] = $this->formatDate($input['invoice_date']);

        DB::beginTransaction();
        try {
            
            //$date = Carbon::createFromFormat('d-m-Y g:i a', $input['invoice_date'])->format('Y-m-d');
            //$invoiceNumber = \App\Models\Invoice::generateInvoiceNumber($input['invoice_date']);
            //dd($fullInput);
            DB::table('invoices')->where('id', $invoice->id)->update($fullInput); 
            DB::table('invoice_consumable_detail')->where('invoice_id', '=', $invoice->id)->delete();
            foreach( $array as $item){
                DB::table('invoice_consumable_detail')->insert([
                    'invoice_id' => $invoiceId,
                    'consumable_id' => $item['consumable_id'],
                    'unit_price' => $item['unit_price'],
                    'qty' => $item['qty'],
                    'amount' => $item['amount'],
                    'created_at' => \Carbon\Carbon::now(),
                    'created_by' => \Auth::user()->id,
                    'cgst' => $this->amount($item, 'cgst'),
                    'sgst' => $this->amount($item, 'sgst'),
                    'igst' => $this->amount($item, 'igst'),
                    'cgst_value' => $this->amount($item, 'cgst_value'),
                    'sgst_value' => $this->amount($item, 'sgst_value'),
                    'igst_value' => $this->amount($item, 'igst_value'),
                    'discount' => $this->amount($item, 'discount'),
                    'net_amount' => $this->amount($item, 'net_amount'),
                    'net_gst' => $this->amount($item, 'net_gst'),
                    'discount_val' => $this->amount($item, 'discount_val')
                ]); 
            }

            $invoice = \App\Models\Invoice::find($invoice->id);

            $entry = \App\Models\Entry::where('invoice_ref_id','=' ,$invoice->id)->first();
            DB::table('entries')->where('invoice_ref_id', $invoice->id)->update([
                'entrytype_id' => 5,
                'ref_number' => $invoice->invoice_number,
                'tr_date' => $fullInput['invoice_date'],
                'dr_total' => 0,
                'cr_total' => $input['totalAmount'],
                'updated_by' => \Auth::user()->id,
                'updated_at' => \Carbon\Carbon::now(),
            ]);
            DB::table('entryitems')->where('entry_id', $entry->id)->delete();
           
            DB::table('entryitems')->insertGetId([
                'entry_id' =>$entry->id,
                'account_id' => $invoice->account_id,
                'dr_total' => 0,
                'cr_total' => $input['totalAmount'],
                'created_at' => \Carbon\Carbon::now(),
            ]);
            
            DB::commit();
            $invoice = \App\Models\Invoice::find($invoiceId);

            return  $this->sendResponse( new \App\Http\Resources\Invoice\InvoiceResource($invoice), 'Consumable Invoice updated successfully.');
            $success = true;
        } catch (\Exception $e) {
            DB::rollback();
            return $this->handleDBException($e);
        } catch (\Throwable $e) {
            DB::rollback();
            return $this->handleDBException($e);
        }   
    }   

}

