<?php



namespace App\Http\Controllers\Api;



use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use App\Models\Quotation;

use App\Models\QuotationItem;

use App\Models\User;

use App\Models\Customers;

use App\Models\SentMail;

use App\Mail\QuotationMail;

use Illuminate\Support\Facades\Mail;

use Illuminate\Support\Facades\Redirect;

use Illuminate\Support\Facades\Http;

use PDF;

use Log;

use Auth;

use Carbon\Carbon;

use App\Service\SequenceService;
use App\Service\SaleItemService;
use App\Models\OrderTracking;
use App\Models\Status;
use App\Models\Order;

class QuotationController extends Controller

{

    public function quotationCreateUpdate(Request $request){
         // Validate Item

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

            'total'=>'required',
            'transaction_date'=>'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',

                'order_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
            $sale_items=new SaleItemService;
            $sequence=new SequenceService;

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

            // 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);

                    // 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->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);

            }     

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

    public function quotationList(Request $request)
    {
        $user=Auth::user();

         // Validate Item

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

            'fy'=>'required',
            // 'warehouse_id'=>'required'
        ]);

        if ($validator->fails()) { 

            return [

                'success' => false, 
                'message' => $validator->errors()->first()

            ];

        } else {

            $quotations= Quotation::with('items','entry_by')
                ->where('fy',$request['fy']);

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

                $quotations = $quotations->where(function ($query) use ($request) {
                    
                    $query->where('quotation_id', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('display_name', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('reference_no', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('total', 'LIKE', '%' . $request['search'] . '%');
                });

            }

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

                $quotations = $quotations->where('order_id',$request['order_id']);

            }

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

                $quotations = $quotations->where('enteredbyid',$request['vendor_id']);

            }

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

                $quotations = $quotations->where('status',$request['status']);

            }

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

                $quotations = $quotations->whereIn('status',$request['statues']);

            }

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

                $quotations = $quotations->where('customer_id',$request['customer_id']);

            }

            // if ($request['expiry_date']==1) {

            //     $today_date = Carbon::now()->format('Y-m-d');

            //     $quotations = $quotations->whereDate('expiry_date','<',$today_date );
                
            // }else if($request['expiry_date']==0){
            //     $today_date = Carbon::now()->format('Y-m-d');

            //     $quotations = $quotations->whereDate('expiry_date','>=',$today_date );
            // }

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

                $customDate = $request->custom_date;

                $quotations = $quotations->whereDate('transaction_date', $customDate);

            }

            // get fromDate toDate data by created_at

            if ($request['from_date']!='' && isset($request['to_date'])) {

                $fromDate = $request->from_date;

                $toDate = $request->to_date;

                // 'fromDate' and 'toDate'

                $quotations = $quotations->whereBetween('transaction_date', [$fromDate, $toDate]);

            }

        
            // sorting by 'quotation_id'

            if ($request->has('quotation')) {

                if ($request->quotation === '1') {

                    $quotations = $quotations->orderBy('quotation_id');

                } elseif ($request->quotation === '0') {

                    $quotations = $quotations->orderByDesc('quotation_id');

                }

            }

            $total=$quotations->count();

            if(isset($request['sort_by']) && $request['sort_by']!='' && $request['sort_by']!=null){
                
                $sort_order=$request['sort_order']==1?'asc':'desc';

                $quotations = $quotations->orderby($request['sort_by'],$sort_order);

            }else{
                $quotations = $quotations->orderby('id','desc');
            }


            $quotations=$quotations->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                    ->get();
                    
            $response=[

                'message'=>'Quotation list fetch Successfully',

                'success'=>true,

                'quotations'=>$quotations,

                'total'=>$total,

            ];



            return response()->json($response);

        }

    }



    public function quotationDetails(Request $request)
    {

        $user=Auth::user();

        // Validate Item

        $validator=validator($request->all(),[
            'id'=>'required'
        ]);

        if ($validator->fails()) { 

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

        } else {

            $quotation = Quotation::where('id',$request['id'])

                ->with('items','customer','customer.address','customer.address.city:id,name',
                    'customer.address.country:id,name','customer.address.state:id,name','items.item')

                ->first();

            $response=[
                'quotation'=>$quotation,
                'message'=>'Details Fetched Successfully',
                'success'=>true
            ];

            return response()->json($response);

        }

    }



    public function send_mail(Request $request)

    {
        $user=Auth::user();

        // Validate Item

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

            'id'=>'required'

        ]);

        if ($validator->fails()) { 

            return [

                'success' => false, 

                'message' => $validator->errors()->first()

            ];

        } else {

            try{

                $quotation = Quotation::where('id',$request['id'])

                    // ->where('organisation_id',$user['active_organisation'])

                    ->with('items','items.item','customer')->firstOrFail();

                // $customer=User::where('id',$quotation['customer_id'])->first();

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

                // Return error message in JSON if ID not found

                return response()->json(['success'=>false,'message' => 'Invalid Id found'], 404);

            }

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

            //     $email=$request['email'];

            // }else if($sale_order!=null){

            //     $email=$sale_order['email'];
                
            // }else{
                $email=$request['to_email'];
            // }
            
            if($email!=null && $email!=''){

                $obj['to_email']=$request['to_email'];
                $obj['subject']=$request['subject'];
                $obj['body']=$request['body'];
                $obj['attachments']=$request['upload_documents'];
                $obj['module_id']=$request['id'];
                $obj['module_type']='quotation';

                $sent_email=SentMail::create($obj);

                $data['email']=$request['to_email'];
                $data['title']='Quotation Details';
                $data['quotation']=$quotation;
                $data['mail_data']=$sent_email;

                // Define the file path to the attachment(s)
                $attachments =json_decode($request['upload_documents'], true);

                Mail::send('quotation.quote', ['data' => $data], function ($message) use ($data, $attachments,$request) {
                    $message->to($data['email'])
                            ->subject($request['subject']);
                    
                    // Log::info($attachments);

                    foreach ($attachments as $attachment) {
                        $url = $attachment['url'];
                        $name = $attachment['name'];
    
                        try {
                            // $url = urldecode($url);
    
                            // Validate URL format
                            if (!filter_var($url, FILTER_VALIDATE_URL)) {
                                Log::error("Invalid URL format: $url");
                                continue;
                            }
    
                            // Fetch the file content
                            $response = Http::get($url);
    
                            if ($response->successful()) {
    
                                $fileContent = $response->body();
                                $contentType = $response->header('Content-Type');
    
                                // Sanitize the filename
                                $fileName = basename(parse_url($url, PHP_URL_PATH));
                                $fileName = $fileName ?: 'attachment.' . mime2ext($contentType);
    
                                // Ensure the filename is safe for attachments
                                $fileName = preg_replace('/[^a-zA-Z0-9\-_\.]/', '_', $fileName);
    
                                // Attach the file content to the email
                                $message->attachData($fileContent, $fileName, [
                                    'mime' => $contentType,
                                ]);
    
                                Log::info("File Attached");
    
                            } else {
                                Log::error("Failed to fetch file from URL: $url", ['status' => $response->status()]);
                            }
                        } catch (\Exception $e) {
    
                            Log::error("Exception occurred while processing URL: $url", ['exception' => $e->getMessage()]);
                        }
                    }
                });

                $quotation->is_mail_sent = 1;
                $quotation->update();

                $response=[

                    'success'=>true,

                    'message'=>'Quotation sent Successfully'

                ];

            } else {

                $response=[

                    'success'=>false,

                    'message'=>'Customer Email Does not Exists'

                ];
            }

            return response()->json($response);

        }



    }


    public function pdf()
    {

        $pdf = PDF::loadView('view');


        // return $pdf->download('sample.pdf');

        return $pdf->stream('quotation.pdf');
    
    }


    public function destroy(Request $request)

    {
        $user=Auth::user();

         // Validate Item

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

            'id'=>'required'

        ]);



        if ($validator->fails()) { 

            return [

                'success' => false, 

                'message' => $validator->errors()->first()

            ];

        } else {



            try{

                $quotation = Quotation::where('id',$request['id'])
                    ->where('organisation_id',$user['active_organisation'])
                    ->first();

                    if($quotation['is_approved']==0){

                        $quotation->delete();
    
                        $quotation_items=QuotationItem::where('transaction_id',$quotation['id'])->get();
        
                        foreach ($quotation_items as $value){
        
                            $value->delete();
        
                        }
        
                        $response=[
        
                            'success'=>true,
        
                            'message'=>'Quotation deleted Successfully'
        
                        ];
    
        
                    }else{
        
                        $response=[
        
                            'success'=>false,
        
                            'message'=>'Quotation is Approved. You can\'t delete this quotation.'
        
                        ];
        
                    }
        
                    return response()->json($response);

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

                // Return error message in JSON if ID not found

                return response()->json(['message' => 'Invalid Id found'], 404);

            }

        }

    }

    public function approveQuotation(Request $request){

        // Validate Item

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

            'id'=>'required'

        ]);

        if ($validator->fails()) { 

            return [

                'success' => false, 

                'message' => $validator->errors()->first()

            ];

        } else {

            try{

                $transaction = Quotation::findOrFail($request->id);

                $transaction['is_approved']=1;
                $transaction['status']=1;

                $transaction->update();  

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

                // Return error message in JSON if ID not found

                return response()->json(['message' => 'Invalid Id to update '], 404);

            }

        }

        $response=[ 
            'success'=>true,
            'message'=>'Quotation Approved Successfully'
        ];

        return response()->json($response);

    }

    public function statusQuotation(Request $request){
        // Validate Item
        $status_change='';

        $validator=validator($request->all(),[
            'id'=>'required',
            'status'=>'required'
        ]);

        if ($validator->fails()) { 

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

        } else {
            $transaction = Quotation::findOrFail($request->id);

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

            if($request['status']==1){
                $status_change='Approved';
                $transaction['is_approved']=1;

                $order=Order::where('id','=',$transaction->order_id)->first();

                //update Order_tracking
                $order_tracking=new OrderTracking;
                $order_tracking->order_id=$order->id;
                $order_tracking->status='Order Creation';
                $order_tracking->status_id=Status::where('name','Like','%Received%')->first()['id'];
                $order_tracking->comments='Quotation Received by the Vendor';
                $order_tracking->sub_status='Quotation Received';
                $order_tracking->save();

                // Update Status on Order
                $order->vendor_id = $request->vendor_id??0;
                $order->status = 'Order Creation';
                $order->sub_status = 'Quotation Received';
                $order->status_id=$order_tracking->status_id;
                $order->save();
            }
            if($request['status']==2){
                $status_change='Declined';
                $transaction['is_approved']=0;
            }
            if($request['status']==0){
                $status_change='Draft';
            }

            $transaction->update();  

            $response=[ 
                'success'=>true,
                'message'=>'Quotation '.$status_change.' Updated Successfully'
            ];

            return response()->json($response);

        }
    }

    // Get details of vendor qutoation
    public function quotationVendorDetails(Request $request)
    {

        $user=Auth::user();

        // Validate Item
        $validator=validator($request->all(),[
            'vendor_id'=>'required',
            'order_id'=>'required'
        ]);

        if ($validator->fails()) { 

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

        } else {

            $quotation = Quotation::where('order_id',$request['order_id'])
                ->where('enteredbyid',$request['vendor_id'])
                ->with('items','customer','customer.address','customer.address.city:id,name',
                    'customer.address.country:id,name','customer.address.state:id,name','items.item')
                ->first();

            if($quotation==null){

                $response=[
                    'quotation'=>$quotation,
                    'message'=>'Details not found',
                    'success'=>false
                ];
            }else{
                $response=[
                    'quotation'=>$quotation,
                    'message'=>'Details Fetched Successfully',
                    'success'=>true
                ];
            }

            return response()->json($response);

        }

    }
}