<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Models\CreditNote;
use App\Models\CreditNoteItem;
use App\Models\DebitNote;
use App\Models\DebitNoteItem;
use App\Service\CreditDebitItemService;
use App\Service\ActivityService;
use App\Service\SequenceService;
use App\Service\StaticMaster;
use App\Models\InvoiceItem;

class CreditDebitController extends Controller
{
    // Creating and Updating Credit and Debit Note 
    public function createUpdate(Request $request){

        // Validate Item
        $validator=validator($request->all(),[
            'tran_type'=>'required|string',
            // 'warehouse_id'=>'required',
            'fy'=>'required',
            'total'=>'required',
            'transaction_date'=>'required',
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {

            $data=[
                'transaction_date',
                'expiry_date',
                'vendor_id',
                'customer_id',
                'invoice_id',
                'bill_id',
                'fy',
                'warehouse_id',
                'vendor_type',
                'vendor_name',
                'display_name',
                'customer_name',
                'phone',
                'email',
                'address',
                'currency',
                'currency_symbol',
                'terms_and_condition',
                'vendor_note',
                'subtotal',
                'total',
                'discount',
                'tcs',
                'shipping_charge',
                'adjustment_charge',
                'charges',
                'reference',
                'reference_no',
                'shipment_date',
                'sale_person',
                'upload_image',
                'status',
                'customer_note',
                'upload_image',
                'reason_type',
                'place_of_supply',
                'exchange_rate',
            ];
            foreach ($data as $key => $value) {
                if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                    $obj[$value]=$request[$value];
                }

                if($request[$value]==''){
                    $obj[$value]=null;
                }

                if($request[$value]==0){
                    $obj[$value]=0;
                }
            }

            $transaction=[];
            $module='';

            // Creating Item Service Object
            $creditdebitService=new CreditDebitItemService;

            // Activity Service
            $activity=new ActivityService;
            $sequence=new SequenceService;

            // Credit Note 
            if($request['tran_type']=='credit_note'){

                $entity='CreditNote';
                $module='credit_note';

                $obj['transaction_type']=StaticMaster::$CREDIT_NOTE;

                if($request['id']>0){

                    try{
                        //Check if id is already exists
                        $transaction=CreditNote::findOrFail($request['id']);

                        //Creating Activities 
                        $activity->activityCreateUpdate('CreditNote',$transaction['id'],'Updated');

                        // Delete Existing Items
                        $CreditNote_item=CreditNoteItem::where('transaction_id',$request['id'])->get();

                        //delete existing items quantity of column credit note quantity from the invoice items
                        foreach ($CreditNote_item as $key => $value) {
                            $invoice_item=InvoiceItem::where('transaction_id',$transaction['invoice_id'])
                                ->where('item_id',$value['item_id'])
                                ->first();
                            if($invoice_item){
                                $invoice_item->update([
                                    'credit_note_qty'=>$invoice_item['credit_note_qty']-$value['quantity']
                                ]);
                            }

                            $value->delete();
                        }

                        // Updating transaction
                        $transaction->update($obj);

                        // Updating items
                        $creditdebitService->saveItems($request,$transaction);

                    } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                        // Return error message in JSON if ID not found
                        return response()->json(['message' => 'Invalid Id to update '], 404);
                    }

                }else{
                    $transaction=CreditNote::create($obj);

                    //Creating Activities 
                    $activity->activityCreateUpdate('Credit Note',$transaction['id'],'Created');

                    // Creating items
                    if(isset($request['items']) && count($request['items'])>0){
                        $creditdebitService->saveItems($request,$transaction);
                    }

                    $transaction['credit_note_id']=$request['credit_note_id'];
                    $transaction->update();

                    // Update Sequence Number
                    $sequence->updateSequence($module);
                }     
            }

            // Debit Note 
            if($request['tran_type']=='debit_note'){

                $entity='DebitNote';
                $module='debit_note';

                $obj['transaction_type']=StaticMaster::$DEBIT_NOTE;

                if($request['id']>0){

                    try{
                        // Check if id exists then update
                        $transaction=DebitNote::findOrFail($request['id']);
                        $transaction->update($obj);

                        //Creating Activities 
                        $activity->activityCreateUpdate('Debit Note',$transaction['id'],'Updated');

                        // Delete Existing Items
                        $DebitNote=DebitNoteItem::where('transaction_id',$request['id'])->delete();

                        // Updating items
                        $creditdebitService->saveItems($request,$transaction);

                    } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                        // Return error message in JSON if ID not found
                        return response()->json(['message' => 'Invalid Id to update '], 404);
                    }

                }else{

                    $transaction=DebitNote::create($obj);

                    //Creating Activities 
                    $activity->activityCreateUpdate('Debit Note',$transaction['id'],'Updated');

                    // Creating items
                    $creditdebitService->saveItems($request,$transaction);

                    $transaction['debit_note_id']=$request['debit_note_id'];
                    $transaction->update();

                    // Update Sequence Number
                    $sequence->updateSequence($module);
                }
            }
        
            return response()->json(['status'=>200,'message'=>'Transaction Created Successfully','data'=>$transaction],200);
        }

    }
}
