<?php

namespace App\Http\Controllers\Api\Sales;

use App\Http\Controllers\Controller;



use App\Models\SaleOrder;

use App\Models\SalesOrderItem;

use App\Models\User;
use App\Models\SaleOrderItem;

use App\Models\Customers;

use Illuminate\Http\Request;

use App\Models\SentMail;

use App\Mail\QuotationMail;

use Illuminate\Support\Facades\Mail;

use Illuminate\Support\Facades\Redirect;

use Illuminate\Support\Facades\Http;

use Auth;

use Log;



class SalesOrderController extends Controller

{

    public function list(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 {



            $salesOrder= SaleOrder::where('organisation_id',$user['active_organisation'])
                // ->where('warehouse_id',$request['warehouse_id'])
                ->where('fy',$request['fy']);

            

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

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

            }


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

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

            }

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

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

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

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

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

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

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

                });

            }
                // get alphabetically data by customer_name

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

                $salesOrder=$salesOrder->orderBy('customer_name');

            }

            // get custom_date data by transaction_date

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

                $customDate = $request->custom_date;

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

            }
            // get last modified data by updated_at

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

                $salesOrder=$salesOrder->orderBy('updated_at');

            }
            // 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'

                $salesOrder = $salesOrder->whereBetween('transaction_date', [$fromDate, $toDate]);
                // $salesOrder = $salesOrder->whereBetween('created_at', [$fromDate.''.'00:00:00', $toDate.''.'00:00:00']);

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

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

            }

            $count=$salesOrder->count();

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

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

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


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

            $response=[

                'message'=>'Sales Order List Fetched Successfully',

                'sale_orders'=>$salesOrder,

                'count'=>$count,

                'success'=>true

            ];



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

        }

    }



    public function details(Request $request)

    {

        $user = Auth::user();



         // Validate Item

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

            'id'=>'required'

        ]);



        if ($validator->fails()) { 

            return [

                'success' => false, 

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

            ];

        } else {



            $salesOrder = SaleOrder::where('id',$request['id'])

                ->where('organisation_id',$user['active_organisation'])
                // ->with('items','customer','items.item','activity')

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

                ->first();

                if ($salesOrder['items']->count() > 0) {
                    foreach ($salesOrder['items'] as $key => $item) {
                        if (!empty($item->service_data)) {
                            $service_data = $item->service_data; // already array

                            // Getting Guests 
                            $guestIds = explode(',', $service_data['guest_ids'] ?? '');
                            $service_data['guests'] = User::whereIn('id', $guestIds)->get();

                            // Laravel will auto re-encode to JSON when saving
                            $item->service_data = $service_data;
                            $item->save();
                        }
                    }
                }



            $response=[

                'salesOrder'=>$salesOrder,

                'items'=>'Details Fetch Successfully',

            ];



            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{

                $sale_order = SaleOrder::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);

            }

            // Send the email
            $email='';

        
            $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']='sale_order';

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

                $data['email']=$email;

                $data['title']='Sales Order Details';

                $data['sale_order']=$sale_order;

                $data['mail_data']=$sent_email;

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

                // Mail::send('sales-order.sales-order', ['data' => $data], function ($message) use ($data) {

                //     $message->to($data['email'])->subject($data['title']);

                // });
                Mail::send('sales-order.sales-order', ['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()]);
                        }
                    }
                });

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

                $response=[

                    'success'=>true,

                    'message'=>'Sales Order sent Successfully'

                ];

            } else {

                $response=[

                    'success'=>false,

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

                ];
            }

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

        }



    }




    public function destroy(Request $request)

    {

        $user=Auth::user();

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

            'id'=>'required',

        ]);

        if ($validator->fails()) { 

            return [

                'success' => false, 

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

            ];

        } else {


            try{

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

                if (!$sale_order) {
                    return response()->json(['message' => 'Invalid Id found'], 404);
                }

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

                // Return error message in JSON if ID not found

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

            }

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

                $sale_order->delete();

                $sale_order_items=SaleOrderItem::where('transaction_id',$sale_order['id'])->get();

            
                foreach ($sale_order_items as $value){

                    $value->delete();

                }

                $response=[

                    'success'=>true,

                    'message'=>'Sale Order deleted Successfully'

                ];

            }else{

                $response=[

                    'success'=>false,

                    'message'=>'Sale Order is Approved. You can\'t delete this sale order.'

                ];

            }
          

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

    }

    public function approveSaleOrder(Request $request){

        

        $validator=Validator::make($request->all(),[

            'id'=>'required'

        ]);



        if ($validator->fails()) {

            # code...

            $response=[ 

                'success'=>false,

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

            ];

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

        else{

            try{

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

                $transaction['is_approved']=1;

                $transaction->update();  

                // $stockEntryService = new StockEntryService;

                // $stockEntryService->saveStockEntries( $transaction,$entity,2);



            } 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'=>'Sale Order Approved Successfully'

        ];



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

    }

    public function statusSaleOrder(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 {

            try{

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

                if (!$transaction) {
                    return response()->json(['message' => 'Invalid Id found'], 404);
                }

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

                if($request['status']==1){
                    $status_change='Approved';
                    $transaction['is_approved']=1;
                }
                if($request['status']==2){
                    $status_change='Declined';
                    $transaction['is_approved']=0;
                }
                if($request['status']==0){
                    $status_change='Draft';
                }

                $transaction->update();  

                $response=[ 

                    'success'=>true,
        
                    'message'=>'Sales Order '.$status_change.' Updated Successfully'
        
                ];
            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

                // Return error message in JSON if ID not found

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

            }

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

        }
    }

}