<?php

namespace App\Observers;

use App\Models\Order;
use App\Models\Product;
use App\Models\Systemlog;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class OrderdataObserver
{
    public function created(Order $order): void
    {

        try {
            $user = Auth::user();
            $userName = $user ? $user->name : 'Guest';
            $message = "New Order " . $order->id . " created  by " . $userName . " at " . now()->toDateTimeString();
            Systemlog::create([
                'message' => $message,
            ]);
        }
        catch (\Exception $e) {
            Systemlog::create([
                'message' => $e->getMessage(),
            ]);
            // Handle the exception here, for example, log the error message
            Log::error('Error in observer: ' . $e->getMessage());
        }
    // Only send to delivery system if order is successful/paid
    //        try {
//             // First, get a waybill ID from the API
//             $waybillId = $this->getWaybillId();
    //             if (!$waybillId) {
//                 Log::error('Could not retrieve waybill ID from API', [
//                     'order_id' => $order->order_id
//                 ]);
//                 return;
//             }
//          $codvalue=0;
//          if($order->payment_method === 'cod'){
//              $codvalue=$order->total + $order->service_fee;
//          }
//          else{
//              $codvalue=0;
//          }
//             // Prepare the data for Koombiyo API
//         $apiData = [
//     'apikey' => 'ORkohpssTIlGBjSqDYyb',
//     'orderWaybillid' => $waybillId,
//     'orderNo' => $order->order_id,
//     'receiverName' => $order->first_name . ' ' . $order->last_name,
//     'receiverStreet' => trim($order->address_1 . ' ' . $order->address_2),
//     'receiverDistrict' => $this->getDistrictId($order->district),
//     'receiverCity' => $this->getCityId($order->city, $order->district),
//     'receiverPhone' => $order->telephone,
//     'description' => $this->getOrderDescription($order),
//     'spclNote' => $order->ordernote ?? 'Order from website',
//     'getCod'=>$codvalue
// ];


    //             Log::info('Sending order to Koombiyo Delivery', [
//                 'order_id' => $order->order_id,
//                 'waybill_id' => $waybillId,
//                 'api_data' => $apiData
//             ]);
    //             // Send POST request to Koombiyo API
//             $response = Http::asForm()->post('https://application.koombiyodelivery.lk/api/Addorders/users', $apiData);

    //             if ($response->successful()) {
//                 // Update order with tracking info
//                 $order->update([
    //                     'koko_order_id' => $waybillId
//                 ]);

    //                 Log::info('Order successfully sent to Koombiyo Delivery', [
//                     'order_id' => $order->order_id,
//                     'waybill_id' => $waybillId,
//                     'response' => $response->json()
//                 ]);
//             } else {
//                 Log::error('Failed to send order to Koombiyo Delivery', [
//                     'order_id' => $order->order_id,
//                     'waybill_id' => $waybillId,
//                     'response' => $response->body(),
//                     'status' => $response->status()
//                 ]);
//             }
    //         } catch (\Exception $e) {
//                  DB::table('error_logs')->insert([
//                 'message' => $th->getMessage(),
//                 'file' => $th->getFile(),
//                 'line' => $th->getLine(),
//                 'trace' => $th->getTraceAsString(),
//                 'created_at' => now(),
//             ]);
//         }
    }

    /**
     * Send order data to Koombiyo Delivery API
     */


    /**
     * Retrieve waybill ID from Koombiyo API
     */    //     private function getWaybillId()
//     {
//         try {
//             $response = Http::asForm()->post('https://application.koombiyodelivery.lk/api/Waybils/users', [
//                 'apikey' => 'ORkohpssTIlGBjSqDYyb',
//                 'limit' => 1
//             ]);
    //           if ($response->successful()) {
//     $data = $response->json();
    //     Log::info('Waybill API Response', ['response' => $data]);
    //     // Check multiple possible response structures
//     if (isset($data['data']) && is_array($data['data']) && count($data['data']) > 0) {
//         return $data['data'][0]['waybill_id'] ?? $data['data'][0]['barcode'] ?? $data['data'][0]['id'];
//     } elseif (isset($data['waybill_id'])) {
//         return $data['waybill_id'];
//     } elseif (isset($data['barcode'])) {
//         return $data['barcode'];
//     } elseif (isset($data['waybills']) && is_array($data['waybills']) && count($data['waybills']) > 0) {
//         return $data['waybills'][0]['waybill_id'] ?? null;
//     }
    //     Log::error('No waybill ID found in API response', ['response' => $data]);
//     return null;
// } else {
//                 Log::error('Failed to get waybill ID - API error', [
//                     'status' => $response->status(),
//                     'response' => $response->body()
//                 ]);
//                 return null;
//             }
//         } catch (\Exception $e) {
//             Log::error('Exception while getting waybill ID from Koombiyo API', [
//                 'error' => $e->getMessage()
//             ]);
//             return null;
//         }
//     }
    //     /**
//      * Get district ID for Koombiyo API
//      */
//     private function getDistrictId($districtName)
//     {
//         // You may want to create a mapping table or cache this data
//         $districtMapping = [
//             'Colombo' => 1,
//             'Gampaha' => 2,
//             'Kalutara' => 3,
//             'Kandy' => 4,
//             'Matale' => 5,
//             'Nuwara Eliya' => 6,
//             'Galle' => 7,
//             'Matara' => 8,
//             'Hambantota' => 9,
//             'Jaffna' => 10,
//             'Kilinochchi' => 11,
//             'Mannar' => 12,
//             'Vavuniya' => 13,
//             'Mullativu' => 14,
//             'Batticaloa' => 15,
//             'Ampara' => 16,
//             'Trincomalee' => 17,
//             'Kurunegala' => 18,
//             'Puttalam' => 19,
//             'Anuradhapura' => 20,
//             'Polonnaruwa' => 21,
//             'Badulla' => 22,
//             'Moneragala' => 23,
//             'Ratnapura' => 24,
//             'Kegalle' => 25
//         ];
    //         return $districtMapping[$districtName] ?? 1; // Default to Colombo
//     }
    //     /**
//      * Get city ID for Koombiyo API
//      */
//     private function getCityId($cityName, $districtName)
//     {
//         // This is a simplified version. You should ideally call the Cities API
//         // or maintain a mapping table for accurate city IDs
//         try {
//             $districtId = $this->getDistrictId($districtName);
//             $response = Http::asForm()->post('https://application.koombiyodelivery.lk/api/Cities/users', [
//                 'apikey' => 'ORkohpssTIlGBjSqDYyb',
//                 'district_id' => $districtId
//             ]);
    //             if ($response->successful()) {
//                 $cities = $response->json();
//                 // Find matching city (adjust based on actual API response structure)
//                 foreach ($cities as $city) {
//                     if (stripos($city['name'], $cityName) !== false) {
//                         return $city['id'];
//                     }
//                 }
//             }
//         } catch (\Exception $e) {
//             Log::error('Failed to get city ID from Koombiyo API', ['error' => $e->getMessage()]);
//         }
    //         return 1; // Default city ID
//     }
    //     /**
//      * Generate order description from order data
//      */
//     private function getOrderDescription(Order $order)
//     {
//         $description = '';
    //         if ($order->productData) {
//             $description = $order->productData->name ?? 'Product';
//         } else {
//             $description = 'Order item';
//         }
    //         if ($order->size) {
//             $description .= ' (Size: ' . $order->size . ')';
//         }
    //         if ($order->color) {
//     $color = $order->color;
//     $colorName = '';
    //     // Map hex codes to color names
//     if ($color == '#A78B8D') {
//         $colorName = 'Marblepink';
//     } else if ($color == '#61A8F8') {
//         $colorName = 'Babyblue';
//     } else if ($color == '#C55C82') {
//         $colorName = 'Pink';
//     } else if ($color == '#FF0000') {
//         $colorName = 'Red';
//     } else if ($color == '#CAD3D0') {
//         $colorName = 'Clear';
//     } else if ($color == '#BA9978') {
//         $colorName = 'Beige';
//     } else if ($color == '#88DB86') {
//         $colorName = 'Applegreen';
//     } else if ($color == '#DEE4EE') {
//         $colorName = 'Marblewhite';
//     } else if ($color == '#BDB8EE') {
//         $colorName = 'Marbleviolet';
//     } else if ($color == '#E9CBB9') {
//         $colorName = 'Marbleorange';
//     } else if ($color == '#FEF250') {
//         $colorName = 'Lemonyellow';
//     } else if ($color == '#D7D0D1') {
//         $colorName = 'Babypink';
//     } else if ($color == '#D2C77D') {
//         $colorName = 'Metallicgold';
//     } else if ($color == '#DAD9C6') {
//         $colorName = 'Buttermilk';
//     } else if ($color == '#E9C500') {
//         $colorName = 'Yellow';
//     } else if ($color == '#D3CBC4') {
//         $colorName = 'Graybeige';
//     } else if ($color == '#0F2D8D') {
//         $colorName = 'Blue';
//     } else if ($color == '#005E3A') {
//         $colorName = 'Green';
//     } else if ($color == '#D6F2E6') {
//         $colorName = 'Marblegreen';
//     } else if ($color == '#BF8BFF') {
//         $colorName = 'Violet';
//     } else if ($color == '#6B4B36') {
//         $colorName = 'Brown';
//     } else if ($color == '#C0C0C0') {
//         $colorName = 'Silver';
//     } else if ($color == '#808080') {
//         $colorName = 'Grey';
//     } else if ($color == '#6CD2FA') {
//         $colorName = 'Skyblue';
//     } else if ($color == '#D09305') {
//         $colorName = 'Orange';
//     } else if ($color == '#13598B') {
//         $colorName = 'Metallicblue';
//     } else if ($color == '#9582BB') {
//         $colorName = 'Metalicviolet';
//     } else if ($color == '#A286F4') {
//         $colorName = 'Purple';
//     } else if ($color == '#62ADE6') {
//         $colorName = 'Marbleblue';
//     } else if ($color == '#80355C') {
//         $colorName = 'Marblered';
//     } else if ($color == '#2FCBD4') {
//         $colorName = 'Avocadogreen';
//     } else if ($color == '#FFA07A') {
//         $colorName = 'Lightorange';
//     } else if ($color == '#DDD3D1') {
//         $colorName = 'Marblebeige';
//     } else if ($color == '#F4C430') {
//         $colorName = 'Saffron';
//     } else if ($color == '#000000') {
//         $colorName = 'Black';
//     } else if ($color == '#D4AF37') {
//         $colorName = 'Marblegold';
//     } else if ($color == '#FFFFFF') {
//         $colorName = 'Purewhite';
//     } else if ($color == '#B4B4B8') {
//         $colorName = 'Metallicsilver';
//     } else if ($color == '#58C3C2') {
//         $colorName = 'Marblegreen';
//     } else if ($color == '#006A4E') {
//         $colorName = 'Bottlegreen';
//     } else if ($color == '#6F4E37') {
//         $colorName = 'Coffee';
//     } else if ($color == '#FFFDD0') {
//         $colorName = 'Cream';
//     } else if ($color == '#A9A9A9') {
//         $colorName = 'Darkgrey';
//     } else if ($color == '#C40233') {
//         $colorName = 'Metalicred';
//     }
    //     // If no match found, use the hex code
//     $displayColor = $colorName ?: $color;
//     $description .= ' (Color: ' . $displayColor . ')';
// }
    //         if ($order->quantity) {
//             $description .= ' (Qty: ' . $order->quantity . ')';
//         }
    //         return $description;
//     }
    /**
     * Handle the Order "updated" event.
     */
    public function updated(Order $order): void
    {
        try {
            $user = Auth::user();
            $userName = $user ? $user->name : 'System/Guest';
            $message = "Order id " . $order->order_id . " updated  by " . $userName . " at " . now()->toDateTimeString();
            Systemlog::create([
                'message' => $message,
            ]);
        }
        catch (\Exception $e) {
            Systemlog::create([
                'message' => $e->getMessage(),
            ]);
            // Handle the exception here, for example, log the error message
            Log::error('Error in observer: ' . $e->getMessage());
        }
    }

    /**
     * Handle the Order "deleted" event.
     */
    public function deleted(Order $order): void
    {
        try {
            $user = Auth::user();
            $userName = $user ? $user->name : 'System/Guest';
            $message = "Order id " . $order->order_id . " deleted  by " . $userName . " at " . now()->toDateTimeString();
            Systemlog::create([
                'message' => $message,
            ]);
        }
        catch (\Exception $e) {
            Systemlog::create([
                'message' => $e->getMessage(),
            ]);
            // Handle the exception here, for example, log the error message
            Log::error('Error in observer: ' . $e->getMessage());
        }
    }

    /**
     * Handle the Order "restored" event.
     */
    public function restored(Order $order): void
    {
    //
    }

    /**
     * Handle the Order "force deleted" event.
     */
    public function forceDeleted(Order $order): void
    {
    //
    }
}
