<?php



namespace App\Http\Controllers\Api\Sales;



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;

class QuotationController 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 {

            Log::info("Active Organisation =".$user['active_organisation']);

            $quotations= Quotation::where('organisation_id',$user['active_organisation'])
                // ->with('items')
                // ->where('warehouse_id',$request['warehouse_id'])
                ->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($request['status']!='' && $request['status']!=null){

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

            }

            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 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 {

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

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

                ->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 ($quotation['items']->count() > 0) {
                    foreach ($quotation['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=[

                '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 store(Request $request)

    // {

    //     // Validate the request data

    //     $request->validate([

    //        'quotation_data' => 'required',

    //        'items' => 'required|array|min:1', // Ensure items is an array and has at least one item

    //         // Add more validation rules as needed

    //     ]);



    //     $data=[

    //         'name'

    //     ];

        

    //     // Assign valiables to objects

    //     $obj=[];



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

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

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

    //         }

    //     }



    //     // Create the quotation

    //     $quotation = Quotation::create($obj);



    //     // Create quotation items

    //     foreach ($request->items as $item) {



    //         $data=[

    //           'name'

    //         ];

    

    //         // Assign valiables to objects

    //         $obj_items=[];

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

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

    //               $obj_items[$value]=$item[$value];

    //            }

    //         }



    //         QuotationItems::create($obj_items);

    //         // Loop end

    //     }



    //     $response=[

    //         'quotation'=>$quotation,

    //         'success'=>true,

    //         'message'=>'Quotation Created Successfully'

    //     ];



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

    // }



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

        }
    }
}