<?php



namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Service\UploadService;

use App\Service\SaleItemService;

use App\Service\StockEntryService;

use App\Service\CurrencyConvertService;

use App\Models\SaleOrder;

use App\Models\Invoice;

use App\Models\Quotation;

use App\Models\QuotationItem;

use App\Models\SaleOrderItem;

use App\Models\InvoiceItem;

use Validator;

use Log;

use App\Service\ActivityService;

use App\Service\SequenceService;

use App\Service\StaticMaster;


class SaleTransactionController extends Controller

{
    // Creating a new sale 

    public function createUpdateSale(Request $request){

        // Validate Item

        $validator=validator($request->all(),[

            'sale_type'=>'required',
            // 'warehouse_id'=>'required',
            'fy'=>'required',
            'total'=>'required',
            'transaction_date'=>'required',
            'currency'=>'required',
            // 'place_of_supply_id'=>'required',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            $data=[

                'transaction_date',

                'customer_id',

                'fy',

                'warehouse_id',

                'customer_type',

                'payment_terms',

                'shipment_date',

                'delivery_method',

                'customer_name',

                'phone',

                'email',

                'address',

                'currency',

                'currency_symbol',

                'expiry_date',

                'due_date',

                'terms_and_condition',

                'customer_note',

                'subtotal',

                'total_tax',

                'total',

                'discount',

                'tcs',

                'shipping_charge',

                'adjustment_charge',

                'charges',

                'reference_no',

                'reference',

                'custom_fields',

                'shipment_date',

                'sale_person',

                'subject',

                'upload_image',

                'status',

                'display_name',

                'tracking_details',

                'place_of_supply',

                'exchange_rate',

                // 'state_id',

                'place_of_supply_id'

            ];


            foreach ($data as $key => $value) {

                if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){

                    $obj[$value]=$request[$value];

                }

                if($request[$value]=='' && $request[$value]==null){

                    $obj[$value]=null;

                }

                if($request[$value]==0){

                    $obj[$value]=0;

                }

            }

            // Serivces to upload and sale items record
            $uploadService=new UploadService;
            $sale_items=new SaleItemService;
            $currency_convert=new CurrencyConvertService;
            $sequence=new SequenceService;

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

            // Quotation 
            if($request['sale_type']=='quotation'){

                Log::info("Quotation creation");

                $entity='Quotation';

                $module='quotation';

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

                    try{

                        //Check if id is already exists

                        $transaction=Quotation::findOrFail($request['id']);

                        $transaction->update($obj);

                        // Creating Activities

                        $activity=new ActivityService;

                        $activity->activityCreateUpdate('Quotation',$transaction['id'],'Updated');

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

                        // Creating items

                        $sale_items->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=Quotation::create($obj);

                    $transaction['quotation_id']=$request['quotation_id'];

                    $transaction['file']= $uploadService->uploadfile($request);

                    $transaction->update();

                    // Creating Activities

                    $activity=new ActivityService;

                    $activity->activityCreateUpdate('Quotation',$transaction['id'],'Created');

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

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

                }     

            }

            // Sale Order 
            if($request['sale_type']=='sale_order'){

                Log::info("Sales Order creation");

                $entity='SaleOrder';

                $module='sale_order';

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

                    try{

                        // Check if id exists then update

                        $transaction=SaleOrder::findOrFail($request['id']);

                        $transaction->update($obj);

                        // Creating Activities

                        $activity=new ActivityService;

                        $activity->activityCreateUpdate('Sales Order',$transaction['id'],'Updated');

                        // Delete Existing Items

                        $slae_order_item=SaleOrderItem::where('transaction_id',$request['id'])->delete();

                        // Creating items

                        $sale_items->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=SaleOrder::create($obj);

                    // Creating Activities

                    $activity=new ActivityService;

                    $activity->activityCreateUpdate('Sales Order',$transaction['id'],'Created');

                    $transaction['sale_order_id']=$request['sale_order_id'];

                    // $transaction['exchange_rate']=$currency_convert->getlatestCurrency($request['currency']);
                    // $transaction['exchange_rate']=$request['currency'];

                    $transaction['file']= $uploadService->uploadfile($request); //service to call an upload  file method from the UploadService class.

                    $transaction->update();


                    // Creating items

                    $sale_items->saveItems($request,$transaction);

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

                }

            }

            // Invoice
            if($request['sale_type']=='invoice'){

                Log::info("Invoice creation");

                $entity='Invoice';

                $module=$request['is_invoice']==1?'invoice':'delivery_challan';

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

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

                    try{

                        // Check if id exists then update
                        $obj['is_invoice']=$request['is_invoice']??0;
                        $obj['challan_type_id']=$request['challan_type_id'];
                        $obj['total_gross_amount']=$request['total_gross_amount']??0;

                        $transaction=Invoice::findOrFail($request['id']);
                        $transaction->update($obj);

                        // Creating Activities
                        $activity=new ActivityService;
                        $activity->activityCreateUpdate('Invoice',$transaction['id'],'Updated');

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

                        // Creating items
                        $sale_items->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=Invoice::create($obj);

                    // Creating Activities
                    $activity=new ActivityService;
                    $activity->activityCreateUpdate('Invoice',$transaction['id'],'Created');

                    $transaction['invoice_id']=$request['invoice_id'];
                    $transaction['is_invoice']=$request['is_invoice']??0;
                    $transaction['is_mail_sent']=$request['is_mail_sent']??0;
                    $transaction['payment_term_day']=$request['payment_term_day'];
                    $transaction['challan_type_id']=$request['challan_type_id'];
                    $transaction['total_gross_amount']=$request['total_gross_amount']??0;     // amount of all items qty*amount for inventory
                    $transaction['file']= $uploadService->uploadfile($request); //service to call an upload  file method from the UploadService class.
                    $transaction->update();

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

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

                }

            }

        }

        return response()->json(['status'=>200,'message'=>'Transaction Created Successfully','transaction'=>$transaction],200);
    }

}