<?php
defined('BASEPATH') or exit('No direct script access allowed');

use Google\Cloud\Firestore\FieldValue;
use Google\Cloud\Core\Timestamp;
use DateTime;

class Product extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        // $this->load->database();
        $this->load->helper('url');
        $this->load->library('session');
        $this->load->model('dashboard_model');
        $this->load->model('common');
    }

    public function settings()
    {
        $data["settings"] = $this->common->readdatafromcollectionbetween("Settings");


        $this->template->template_render('settings', $data);
    }
    public function saveSettings($id)
    {
        $post = $this->input->post();
        $response = $this->common->updatedatamodel("Settings", $id, $post);
        if ($response) {
            $this->session->set_flashdata('successmessage', 'Settings has been updated');
        } else {
            $this->session->set_flashdata('warningmessage', 'Error! Some issue with firebase.Please try again');
        }

        redirect(base_url('dashboard/settings'));
    }



    public function index()
    {
        $this->load->library('session');
        $sessionData = $this->session->userdata('session_data');

        if (!$sessionData || !isset($sessionData['userId'])) {
            redirect(base_url('login'));
        }

        try {
            $firebase = $this->firebase->init();
            $db = $firebase->createFirestore()->database();

            // Fetch products for current user
            $productsQuery = $db->collection('TailerServices')
                ->where('tailorId', '==', $sessionData['userId'])
                ->documents();

            // Fetch all categories
            $categories = $db->collection('Categories')->documents();
            $categoryMap = [];
            foreach ($categories as $cat) {
                $categoryMap[$cat->id()] = $cat->data()['name'] ?? 'Uncategorized';
            }

            // Process products data
            $products = [];
            foreach ($productsQuery as $doc) {
                $product = $doc->data();
                $products[] = [
                    'id' => $doc->id(),
                    'image' => $product['image'] ?? '',
                    'serviceName' => $product['serviceName'] ?? '',
                    'category' => $categoryMap[$product['categoryId']] ?? 'Unknown',
                    'date' => isset($product['date']) ? date('d M Y', $product['date'] / 1000) : 'N/A',
                    'shopLocation' => $product['shopLocation'] ?? '',
                    'price' => isset($product['price']) ? 'AED ' . number_format($product['price'], 2) : 'AED 0.00'
                ];
            }

            $data = [
                'userdetails' => $sessionData,
                'products' => $products
            ];

            $this->template->template_render('catalouge', $data);
        } catch (Exception $e) {
            $this->session->set_flashdata('warningmessage', 'Error loading catalogue: ' . $e->getMessage());
            redirect(base_url('dashboard'));
        }
    }

    public function addProduct()
    {
        $this->load->library('session');
        $sessionData = $this->session->userdata('session_data');

        if (!$sessionData || !isset($sessionData['userId'])) {
            redirect(base_url('login'));
        }

        try {
            $firebase = $this->firebase->init();
            $firestore = $firebase->createFirestore();
            $db = $firestore->database();

            // Fetch categories
            $categories = $db->collection('Categories')->documents();
            $categoryList = [];
            foreach ($categories as $category) {
                $categoryList[] = [
                    'id' => $category->id(),
                    'name' => $category->data()['name'] ?? 'Unnamed Category'
                ];
            }

            $data = [
                'userdetails' => $sessionData,
                'categories' => $categoryList
            ];

            $this->template->template_render('addproduct', $data);
        } catch (Exception $e) {
            $this->session->set_flashdata('warningmessage', 'Error loading form: ' . $e->getMessage());
            redirect(base_url('dashboard'));
        }
    }

    public function updateProduct($id)
    {
        $this->load->library('session');
        $sessionData = $this->session->userdata('session_data');

        if (!$sessionData || !isset($sessionData['userId'])) {
            redirect(base_url('login'));
        }

        try {
            $firebase = $this->firebase->init();
            $db = $firebase->createFirestore()->database();

            // Fetch product by ID
            $doc = $db->collection('TailerServices')->document($id)->snapshot();
            if (!$doc->exists()) {
                show_404();
            }

            $product = $doc->data();
            $product['id'] = $doc->id();

            // Fetch categories
            $categories = $db->collection('Categories')->documents();

            $data = [
                'product' => $product,
                'categories' => array_map(function ($cat) {
                    return ['id' => $cat->id(), 'name' => $cat->data()['name']];
                }, iterator_to_array($categories)),
            ];

            $this->template->template_render('update_product', $data);
        } catch (Exception $e) {
            $this->session->set_flashdata('warningmessage', 'Error loading product: ' . $e->getMessage());
            redirect(base_url('catalogue'));
        }
    }

    public function editProduct()
    {
        $this->load->library('session');
        header('Content-Type: application/json');

        $sessionData = $this->session->userdata('session_data');
        if (!$sessionData || !isset($sessionData['userId'])) {
            echo json_encode(['success' => false, 'message' => 'Unauthorized']);
            return;
        }

        $firebase = $this->firebase->init();
        $db = $firebase->createFirestore()->database();
        $storage = $firebase->createStorage();
        $bucket = $storage->getBucket();

        try {
            $productId = $this->input->post('product_id');
            if (!$productId) {
                throw new Exception("Invalid product ID");
            }

            // Fetch the existing product
            $docRef = $db->collection('TailerServices')->document($productId);
            $docSnapshot = $docRef->snapshot();
            if (!$docSnapshot->exists()) {
                throw new Exception("Product not found");
            }

            $existingData = $docSnapshot->data();
            $userId = $sessionData['userId'];

            // Prepare update data
            $updatedData = [
                'serviceName' => $this->input->post('service_name'),
                'categoryId' => $this->input->post('category_id'),
                'detail' => $this->input->post('detail'),
                'price' => floatval($this->input->post('price')),
            ];

            // If a new image is uploaded
            if (!empty($_FILES['product_image']['name'])) {
                $fileTmpPath = $_FILES['product_image']['tmp_name'];
                $fileName = uniqid() . '_' . $_FILES['product_image']['name'];
                $bucket = $storage->getBucket();

                $uploadedFile = $bucket->upload(fopen($fileTmpPath, 'r'), [
                    'name' => 'Products/' . $sessionData['userId'] . '/' . $fileName,
                    'predefinedAcl' => 'publicRead'
                ]);

                $imageUrl = 'https://storage.googleapis.com/' . $bucket->name() . '/Products/' . $sessionData['userId'] . '/' . $fileName;
                $updatedData['image'] = $imageUrl;
            }

            // Convert to Firestore format
            $updateArray = [];
            foreach ($updatedData as $key => $value) {
                $updateArray[] = ['path' => $key, 'value' => $value];
            }

            // Perform the update
            $docRef->update($updateArray);



            echo json_encode([
                'success' => true,
                'message' => 'Product updated successfully!',
                'redirect' => base_url('product')
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ]);
        }
    }




    public function delete($id)
    {
        header('Content-Type: application/json');
        $this->load->library('session');

        $sessionData = $this->session->userdata('session_data');
        if (!$sessionData || !isset($sessionData['userId'])) {
            echo json_encode(['success' => false, 'message' => 'Unauthorized.']);
            return;
        }

        try {
            $firebase = $this->firebase->init();
            $db = $firebase->createFirestore()->database();

            $db->collection('TailerServices')->document($id)->delete();

            echo json_encode(['success' => true, 'message' => 'Product deleted successfully.']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
    }


    public function saveProduct()
    {
        $this->load->library('session');
        header('Content-Type: application/json');

        $sessionData = $this->session->userdata('session_data');
        if (!$sessionData || !isset($sessionData['userId'])) {
            echo json_encode(['success' => false, 'message' => 'User not authenticated.']);
            return;
        }

        try {
            $firebase = $this->firebase->init();
            $firestore = $firebase->createFirestore();
            $storage = $firebase->createStorage();
            $db = $firestore->database();
            $defaultBucket = $storage->getBucket();

            $userId = $sessionData['userId'];
            $imageUrl = '';

            // **🔥 Upload image to Firebase Storage inside "Products/{userId}/" folder**
            if (!empty($_FILES['product_image']['name'])) {
                try {
                    // Generate unique file path
                    $file_name = 'Products/' . $userId . '/' . uniqid() . '_' . $_FILES['product_image']['name'];

                    // Upload to Firebase Storage
                    $uploadedFile = $defaultBucket->upload(
                        file_get_contents($_FILES['product_image']['tmp_name']),
                        ['name' => $file_name, 'predefinedAcl' => 'publicRead']
                    );

                    if ($uploadedFile) {
                        $imageUrl = 'https://storage.googleapis.com/' . $defaultBucket->name() . '/' . $file_name;
                    }
                } catch (Exception $e) {
                    echo json_encode(['success' => false, 'message' => 'Image upload failed: ' . $e->getMessage()]);
                    return;
                }
            }

            // Generate unique Firestore document ID
            $docRef = $db->collection('TailerServices')->newDocument();
            $documentId = $docRef->id();

            $milliseconds = (int) (microtime(true) * 1000);

            // **Prepare product data**
            $productData = [
                'id' => $documentId,
                'serviceName' => $this->input->post('service_name'),
                'categoryId' => $this->input->post('category_id'),
                'detail' => $this->input->post('detail'),
                'price' => (float)$this->input->post('price'),
                'amount' => (float)$this->input->post('price'),
                'shopLocation' => $this->input->post('shop_location'),
                'image' => $imageUrl,  // **🔥 Stores Firebase image URL**
                'tailorId' => $userId,
                'date' => $milliseconds,
            ];

            // **Save product data in Firestore**
            $docRef->set($productData);

            echo json_encode([
                'success' => true,
                'message' => 'Product added successfully!',
                'redirect' => base_url('product') // Redirect URL
            ]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error saving product: ' . $e->getMessage()]);
        }
    }


    // public function orders()
    // {
    //     $this->load->library('session');
    //     $sessionData = $this->session->userdata('session_data');

    //     if (!$sessionData || !isset($sessionData['userId'])) {
    //         redirect(base_url('login'));
    //     }

    //     try {
    //         $firebase = $this->firebase->init();
    //         $db = $firebase->createFirestore()->database();

    //         $processedQuery = $db->collection('Orders')
    //             ->where('vendorId', '==', $sessionData['userId'])
    //             ->where('orderStatus', '==', 'processed')
    //             ->documents();

    //         $processQuery = $db->collection('Orders')
    //             ->where('vendorId', '==', $sessionData['userId'])
    //             ->where('orderStatus', '==', 'process')
    //             ->documents();

    //         // Merge and process results
    //         $orders = [];
    //         $orderNumber = 1;

    //         foreach ($processedQuery as $doc) {
    //             $orders[] = $this->processOrder($doc, $orderNumber++);
    //         }

    //         foreach ($processQuery as $doc) {
    //             $orders[] = $this->processOrder($doc, $orderNumber++);
    //         }

    //         $data = [
    //             'userdetails' => $sessionData,
    //             'orders' => $orders
    //         ];

    //         $this->template->template_render('orders', $data);

    //     } catch (Exception $e) {
    //         $this->session->set_flashdata('warningmessage', 'Error loading orders: ' . $e->getMessage());
    //         redirect(base_url('dashboard'));
    //     }
    // }

    // private function processOrder($doc, $orderNumber)
    // {
    //     $orderData = $doc->data();
    //     return [
    //         'orderId' => $doc->id(),
    //         'orderNumber' => 'Order #' . $orderNumber,
    //         // 'image' => $orderData['items'][0]['image'] ?? base_url('assets/images/su1.png'),
    //         // 'date' => isset($orderData['timestamp']) ? date('M d, Y', $orderData['timestamp']->get()->getTimestamp()) : 'N/A',
    //         // 'status' => $orderData['orderStatus'],
    //         // 'price' => isset($orderData['totalAmount']) ? 'AED ' . number_format($orderData['totalAmount'], 2) : 'AED 0.00'
    //     ];
    // }

    public function orders()
    {
        $this->load->library('session');
        $sessionData = $this->session->userdata('session_data');

        if (!$sessionData || !isset($sessionData['userId'])) {
            redirect(base_url('login'));
        }

        try {
            $firebase = $this->firebase->init();
            $db = $firebase->createFirestore()->database();
            $vendorId = $sessionData['userId'];

            // Fetch all orders for the vendor
            $ordersQuery = $db->collection('Orders')
                ->where('vendorId', '==', $vendorId)
                ->documents();

            // Categorize orders
            $newOrders = [];
            $readyOrders = [];
            $completedOrders = [];
            $orderNumber = 1;

            foreach ($ordersQuery as $doc) {
                $order = $this->processOrder($doc, $orderNumber++);
                switch ($order['status']) {
                    case 'process':
                        // case 'processed':
                        $newOrders[] = $order;
                        break;
                    case 'processed':
                        $readyOrders[] = $order;
                        break;
                    case 'deliver':
                        $completedOrders[] = $order;
                        break;
                }
            }

            $data = [
                'userdetails' => $sessionData,
                'newOrders' => $newOrders,
                'readyOrders' => $readyOrders,
                'completedOrders' => $completedOrders
            ];

            $this->template->template_render('orders', $data);
        } catch (Exception $e) {
            $this->session->set_flashdata('warningmessage', 'Error loading orders: ' . $e->getMessage());
            redirect(base_url('dashboard'));
        }
    }

    private function processOrder($doc, $orderNumber)
    {
        $orderData = $doc->data();
        return [
            'orderId' => $doc->id(),
            'orderNumber' => 'Order #' . $orderNumber,
            'image' => $orderData['productsData'][0]['image'] ?? base_url('assets/images/su1.png'),
            // 'date' => isset($orderData['date']) ? date('M d, Y', $orderData['date'] / 1000) : 'N/A',
            'status' => $orderData['orderStatus'],
            'price' => isset($orderData['price']) ? 'AED ' . number_format($orderData['price'], 2) : 'AED 0.00',
            'address' => implode(', ', array_filter([
                $orderData['address']['streetAddress1'] ?? '',
                $orderData['address']['city'] ?? '',
                $orderData['address']['state'] ?? ''
            ]))
        ];
    }




    public function orderDetails($orderId)
    {
        try {
            $firebase = $this->firebase->init();
            $db = $firebase->createFirestore()->database();
            $orderRef = $db->collection('Orders')->document($orderId);
            $orderDoc = $orderRef->snapshot();

            if (!$orderDoc->exists()) {
                throw new Exception('Order not found');
            }

            $orderData = $orderDoc->data();

            // Process address information
            $address = $orderData['address'] ?? [];
            $addressString = implode(', ', array_filter([
                $address['streetAddress1'] ?? '',
                $address['streetAddress2'] ?? '',
                $address['city'] ?? '',
                $address['state'] ?? '',
                $address['country'] ?? ''
            ]));

            // Process products data
            $products = [];
            $totalQuantity = 0;
            $subTotal = 0;

            foreach ($orderData['productsData'] ?? [] as $product) {
                $products[] = [
                    'image' => $product['image'] ?? '',
                    'name' => $product['serviceName'] ?? 'Unnamed Product',
                    'price' => number_format($product['price'] ?? 0, 2),
                    'quantity' => $product['amount'] ?? 0,
                    'total' => number_format(($product['price'] ?? 0) * ($product['amount'] ?? 0), 2)
                ];
                $totalQuantity += $product['amount'] ?? 0;
                $subTotal += ($product['price'] ?? 0) * ($product['amount'] ?? 0);
            }

            // Process timeline
            $timeline = [];
            foreach ($orderData['track'] ?? [] as $event) {
                $timeline[] = [
                    'date' => date('M d, Y h:i A', $event['date'] / 1000),
                    'event' => $event['name'] ?? 'Unknown Event'
                ];
            }






            // Get delivery date
            // $deliveryDate = isset($orderData['deliveryDate'])
            //     ? date('Y-m-d', strtotime($orderData['deliveryDate']))
            //     : null;

            $deliveryDate = isset($orderData['deliveryDate'])
                ? date('Y-m-d', $orderData['deliveryDate'] / 1000)
                : null;

            // print_r($deliveryDate);
            // die;



            $data = [
                'order' => [
                    'id' => $orderId,
                    'status' => $orderData['orderStatus'] ?? 'Unknown',
                    'orderDate' => date('M d, Y h:i A', $orderData['date'] / 1000),
                    'deliveryDate' => $deliveryDate,
                    'address' => $addressString,
                    'paymentId' => $orderData['pm_id'] ?? 'N/A',
                    'products' => $products,
                    'timeline' => $timeline,
                    'subTotal' => number_format($subTotal, 2),
                    'total' => number_format($orderData['price'] ?? $subTotal, 2),
                    'totalQuantity' => $totalQuantity
                ]
            ];


            //   print_r($data);
            //   die;

            $this->template->template_render('order_details', $data);
        } catch (Exception $e) {
            $this->session->set_flashdata('warningmessage', 'Error: ' . $e->getMessage());
            redirect(base_url('orders'));
        }
    }

    // public function setDeliveryDate($orderId)
    // {
    //     header('Content-Type: application/json');

    //     try {
    //         $firebase = $this->firebase->init();
    //         $db = $firebase->createFirestore()->database();

    //         $deliveryDate = $this->input->post('delivery_date');
    //         $dateObject = new DateTime($deliveryDate);

    //         $updates = [
    //             // ['path' => 'deliveryDate', 'value' => $dateObject->format('Y-m-d')],
    //             ['path' => 'deliveryDate', 'value' => $dateObject->getTimestamp() * 1000], 

    //             ['path' => 'track', 'value' => FieldValue::arrayUnion([
    //                 [
    //                     'date' => new Timestamp(new DateTime()),
    //                     'name' => 'Delivery Date Set'
    //                     // 'userId' => $this->session->userdata('session_data')['userId']
    //                 ]
    //             ])]
    //         ];

    //         $db->collection('Orders')->document($orderId)->update($updates);

    //         echo json_encode(['success' => true]);
    //     } catch (Exception $e) {
    //         echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    //     }
    // }

    public function setDeliveryDate($orderId)
    {
        header('Content-Type: application/json');

        try {
            $firebase = $this->firebase->init();
            $db = $firebase->createFirestore()->database();

            $deliveryDate = $this->input->post('delivery_date');
            $dateObject = new DateTime($deliveryDate);

            $currentTimestampMillis = round(microtime(true) * 1000); // Epoch in milliseconds

            $updates = [
                ['path' => 'deliveryDate', 'value' => $dateObject->getTimestamp() * 1000],
                ['path' => 'track', 'value' => FieldValue::arrayUnion([
                    [
                        'date' => $currentTimestampMillis,
                        'name' => 'Delivery Date Set'
                    ]
                ])]
            ];

            $db->collection('Orders')->document($orderId)->update($updates);

            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
    }


    // public function updateOrderStatus($orderId)
    // {
    //     header('Content-Type: application/json');

    //     try {
    //         $firebase = $this->firebase->init();
    //         $db = $firebase->createFirestore()->database();

    //         // Read input JSON
    //         $json = file_get_contents('php://input');
    //         $data = json_decode($json, true);

    //         if (!isset($data['status'])) {
    //             throw new Exception('Missing status in request body');
    //         }

    //         $newStatus = $data['status'];

    //         // Check if order exists
    //         $orderDoc = $db->collection('Orders')->document($orderId)->snapshot();
    //         if (!$orderDoc->exists()) {
    //             throw new Exception('Order not found');
    //         }

    //         // Debugging: Log Firestore Data
    //         error_log('Order Data: ' . print_r($orderDoc->data(), true));

    //         // Validate status change
    //         $validStatuses = ['process', 'processed', 'readyToDeliver', 'deliver'];
    //         if (!in_array($newStatus, $validStatuses)) {
    //             throw new Exception('Invalid status selected');
    //         }


    //         if ($newStatus === 'readyToDeliver' && empty($orderDoc->data()['deliveryDate'])) {
    //             throw new Exception('Delivery date must be set before marking as Ready To Deliver');
    //         }

    //         $milliseconds = (int) (microtime(true) * 1000);
    //         $db->collection('Orders')->document($orderId)->update([
    //             ['path' => 'orderStatus', 'value' => $newStatus],
    //             ['path' => 'track', 'value' => FieldValue::arrayUnion([
    //                 [
    //                     'date' => $milliseconds,
    //                     'name' => 'Status Changed to ' . ucfirst($newStatus)
    //                 ]
    //             ])]
    //         ]);

    //         echo json_encode(['success' => true]);
    //     } catch (Exception $e) {
    //         error_log('Update Order Status Error: ' . $e->getMessage());

    //         echo json_encode([
    //             'success' => false,
    //             'message' => 'Error updating order: ' . $e->getMessage()
    //         ]);
    //     }
    // }

    // public function updateOrderStatus($orderId)
    // {
    //     header('Content-Type: application/json');

    //     try {
    //         $firebase = $this->firebase->init();
    //         $db = $firebase->createFirestore()->database();

    //         $json = file_get_contents('php://input');
    //         $data = json_decode($json, true);

    //         if (!isset($data['status'])) {
    //             throw new Exception('Missing status in request body');
    //         }

    //         $newStatus = $data['status'];

    //         $orderDocRef = $db->collection('Orders')->document($orderId);
    //         $orderDoc = $orderDocRef->snapshot();
    //         if (!$orderDoc->exists()) {
    //             throw new Exception('Order not found');
    //         }

    //         $validStatuses = ['process', 'processed', 'readyToDeliver', 'deliver'];
    //         if (!in_array($newStatus, $validStatuses)) {
    //             throw new Exception('Invalid status selected');
    //         }

    //         if ($newStatus === 'readyToDeliver' && empty($orderDoc->data()['deliveryDate'])) {
    //             throw new Exception('Delivery date must be set before marking as Ready To Deliver');
    //         }

    //         $milliseconds = (int) (microtime(true) * 1000);
    //         $orderDocRef->update([
    //             ['path' => 'orderStatus', 'value' => $newStatus],
    //             ['path' => 'track', 'value' => FieldValue::arrayUnion([
    //                 [
    //                     'date' => $milliseconds,
    //                     'name' => 'Status Changed to ' . ucfirst($newStatus)
    //                 ]
    //             ])]
    //         ]);


    //         $userId = $orderDoc->data()['userId'];
    //         $userInfo = $this->common->readdatadocument('Users', $userId);
    //         if ($userInfo && !empty($userInfo['token'])) {
    //             $token = $userInfo['token'];
    //             $title = "Order Info";
    //             $body = "Your order status has been changed to " . ucfirst($newStatus);

    //             $notificationData = [
    //                 'senderId' => "",
    //                 'timestamp' => $milliseconds,
    //                 'type' => "order",
    //                 'message' => $body,
    //                 'title' => $title,
    //                 'userIds' => [$userId],
    //                 'orderId' => $orderId
    //             ];
    //             $this->common->addnewdatamodel('Notifications', $notificationData);


    //             $this->send_push_notification($token, $title, $body, $orderId, $newStatus);
    //         }

    //         echo json_encode(['success' => true]);
    //     } catch (Exception $e) {
    //         error_log('Update Order Status Error: ' . $e->getMessage());
    //         echo json_encode([
    //             'success' => false,
    //             'message' => 'Error updating order: ' . $e->getMessage()
    //         ]);
    //     }
    // }

    public function updateOrderStatus($orderId)
{
    header('Content-Type: application/json');

    try {
        $firebase = $this->firebase->init();
        $db = $firebase->createFirestore()->database();

        $json = file_get_contents('php://input');
        $data = json_decode($json, true);

        if (!isset($data['status'])) {
            throw new Exception('Missing status in request body');
        }

        $newStatus = $data['status'];

        $orderDocRef = $db->collection('Orders')->document($orderId);
        $orderDoc = $orderDocRef->snapshot();
        if (!$orderDoc->exists()) {
            throw new Exception('Order not found');
        }

        $validStatuses = ['process', 'processed', 'readyToDeliver', 'deliver'];
        if (!in_array($newStatus, $validStatuses)) {
            throw new Exception('Invalid status selected');
        }

        if ($newStatus === 'readyToDeliver' && empty($orderDoc->data()['deliveryDate'])) {
            throw new Exception('Delivery date must be set before marking as Ready To Deliver');
        }

        $milliseconds = (int) (microtime(true) * 1000);
        $orderDocRef->update([
            ['path' => 'orderStatus', 'value' => $newStatus],
            ['path' => 'track', 'value' => FieldValue::arrayUnion([
                [
                    'date' => $milliseconds,
                    'name' => 'Status Changed to ' . ucfirst($newStatus)
                ]
            ])]
        ]);

        $userId = $orderDoc->data()['userId'];
        $userInfo = $this->common->readdatadocument('Users', $userId);
        if ($userInfo && !empty($userInfo['token'])) {
            $token = $userInfo['token'];
            $title = "Order Info";

            // Customize the notification message based on status
            if ($newStatus === 'deliver') {
                $body = "Your order has been delivered successfully.";
            } else {
                $body = "Your order status has been changed to " . ucfirst($newStatus);
            }

            $notificationData = [
                'senderId' => "",
                'timestamp' => $milliseconds,
                'type' => "order",
                'message' => $body,
                'title' => $title,
                'userIds' => [$userId],
                'orderId' => $orderId
            ];
            $this->common->addnewdatamodel('Notifications', $notificationData);

            $this->send_push_notification($token, $title, $body, $orderId, $newStatus);
        }

        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        error_log('Update Order Status Error: ' . $e->getMessage());
        echo json_encode([
            'success' => false,
            'message' => 'Error updating order: ' . $e->getMessage()
        ]);
    }
}




    public function send_push_notification($tokenId, $title, $body, $orderid, $type)
    {
        // Example device token
        $deviceToken = $tokenId;

        // Notification details
        $data = [
            'orderId' => $orderid,
            'status' => $type,
            'type' => 'order'
        ];

        // Send the notification
        $result = $this->firebase->sendPushNotification($deviceToken, $title, $body, $data);
        // Log result for debugging if needed
        if ($result['success']) {
            error_log("Notification sent successfully. Result: " . print_r($result['result'], true));
        } else {
            error_log("Failed to send notification. Error: " . $result['error']);
        }

        // // Display result
        // if ($result['success']) {
        //     echo "Notification sent successfully!<br>";
        //     echo "Result: " . print_r($result['result'], true);
        // } else {
        //     echo "Failed to send notification!<br>";
        //     echo "Error: " . $result['error'];
        // }
    }



    // public function size()
    // {

    //     $sessionData = $this->session->userdata('session_data');


    //     $data['userdetails'] = $sessionData;

    //     $this->template->template_render('size', $data);
    // }

    public function size($orderId)
    {
        $firebase = $this->firebase->init();
        $firestore = $firebase->createFirestore();
        $db = $firestore->database();

        // Get order by ID
        $orderRef = $db->collection('Orders')->document($orderId);
        $orderSnapshot = $orderRef->snapshot();
        $orderData = $orderSnapshot->data();

        // Get product and its sizeId
        $productData = $orderData['productsData'][0]; // Assuming 1 product per order
        $sizeId = $productData['sizeId'] ?? null;

        $sizeData = [];
        if ($sizeId) {
            $sizeRef = $db->collection('Sizes')->document($sizeId);
            $sizeSnapshot = $sizeRef->snapshot();
            if ($sizeSnapshot->exists()) {
                $sizeData = $sizeSnapshot->data();
            }
        }

        // print_r($sizeData);
        // die;

        $this->template->template_render('size', [
            'order' => $orderData,
            'sizeData' => $sizeData,
        ]);
    }
}
