<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PricingController extends Controller
{
public function getPricingData(Request $request)
{
    // Get the vendor ID from the request
    $vendorId = $request->input('vendor_id');

    // Retrieve vendor information based on the user ID
    $vendor = DB::table('vendors')->select('services', 'user_id', 'opening_hours')->where('user_id', $vendorId)->first();

    // Check if the vendor exists
    if (!$vendor) {
        return response()->json(['message' => 'Vendor not found.'], 404);
    }

    // Decode available services
    $availableServices = json_decode($vendor->services, true);
    if (empty($availableServices)) {
        return response()->json(['message' => 'No services available for this vendor.'], 404);
    }

    // Retrieve pricing data for the vendor
    $pricingData = DB::table('pricing')
        ->join('items', 'pricing.item_id', '=', 'items.id')
        ->join('services', 'pricing.service_id', '=', 'services.id')
        ->where('pricing.vendor_id', $vendorId)
        ->whereIn('services.name', array_values($availableServices))
        ->select('items.id as item_id', 'services.id as service_id', 'services.name as service_name', 'items.name as item_name', 'pricing.customer_price', 'pricing.commission')
        ->get();

    // Retrieve kg pricing data
    $kgPricingData = DB::table('clothing_counts')
        ->where('vendor_id', $vendorId)
        ->select('id', 'customer_price', 'vendor_price', 'per_kg_count', 'created_at', 'updated_at')
        ->get();

    // Format pricing data
    $formattedData = [];

    foreach ($pricingData as $data) {
        if (!isset($formattedData[$data->service_id])) {
            $formattedData[$data->service_id] = [
                'service_id' => $data->service_id, // Service ID
                'name' => $data->service_name, // Service Name
                'items' => [], // Initialize items array
            ];
        }
        $formattedData[$data->service_id]['items'][] = [
            'id' => $data->item_id,
            'name' => $data->item_name,
            'price' => $data->customer_price,
        ];
    }

    // Add kg pricing data
    if (!$kgPricingData->isEmpty()) {
        $formattedData['Laundry by KG'] = [
            'service_id' => $data->service_id, // Or assign a specific ID if available
            'name' => 'Laundry by KG',
            'items' => [],
        ];
        foreach ($kgPricingData as $kgData) {
            $formattedData['Laundry by KG']['items'][] = [
                'id' => $kgData->id,
                'name' => 'Per KG',
                'price' => $kgData->customer_price,
            ];
        }
    }

    // Retrieve user details using user_id from vendor
    $userId = $vendor->user_id;
    $userDetails = DB::table('users')
        ->select('id', 'name', 'phone_number', 'email', 'otp', 'password', 'role', 'referral_code', 'user_id', 'remember_token', 'otp_expiration', 'created_at', 'updated_at', 'wallet')
        ->where('user_id', $userId)
        ->first();

    // Retrieve vendor details
    $vendorDetails = DB::table('vendors')
        ->select('id', 'user_id', 'store_name', 'complete_address', 'gstin', 'longitude', 'latitude', 'services', 'pan', 'balance', 'store_adhar', 'store_documents', 'store_pictures', 'store_selfies', 'profile_image', 'online_status', 'approval_status', 'reason', 'total_orders', 'opening_hours', 'created_at', 'updated_at')
        ->where('user_id', $userId)
        ->first();

    // Convert string representations of JSON to actual JSON objects
    $vendorDetails->services = json_decode($vendorDetails->services, true);
    $decodeAndCleanImages = function ($field) {
    // Remove unwanted slashes and quotes
    $field = stripslashes($field);
    $field = trim($field, '"');

    // Decode JSON string into an array
    $decoded = json_decode($field, true);

    // Ensure it returns an array, even if decoding fails
    if (is_array($decoded)) {
        return $decoded;
    }

    // Handle the case where it's still a string
    return explode(',', $field);
};


$vendorDetails->store_adhar = $decodeAndCleanImages($vendorDetails->store_adhar);
$vendorDetails->store_documents = $decodeAndCleanImages($vendorDetails->store_documents);
$vendorDetails->store_pictures = $decodeAndCleanImages($vendorDetails->store_pictures);
$vendorDetails->store_selfies = $decodeAndCleanImages($vendorDetails->store_selfies);
$vendorDetails->profile_image = $decodeAndCleanImages($vendorDetails->profile_image);

    // Format opening hours
    $openingHours = json_decode($vendor->opening_hours, true);
    $formattedOpeningHours = [];
    if (!empty($openingHours)) {
        foreach ($openingHours as $day => $timing) {
            $formattedOpeningHours[] = [
                'day' => $day,
                'timing' => $timing,
            ];
        }
    }

    // Transform services into the desired format with IDs
    $serviceNames = array_values($vendorDetails->services);
    $serviceIds = DB::table('services')->whereIn('name', $serviceNames)->select('id', 'name')->get();
    
    $formattedServices = [];
    foreach ($serviceIds as $service) {
        $formattedServices[] = [
            'id' => $service->id,
            'name' => $service->name,
        ];
    }

    // Combine all the details into the response
    return response()->json([
        'pricing_data' => array_values($formattedData),
        'user_details' => $userDetails,
        'vendor_details' => array_merge((array) $vendorDetails, [
            'services' => $formattedServices,
            'opening_hours' => $formattedOpeningHours
        ]),
    ], 200);
}
// public function getPricingData(Request $request)
// {
//     $vendorId = $request->input('vendor_id');

//     // Retrieve vendor information
//     $vendor = DB::table('vendors')->select('services', 'user_id', 'opening_hours')->where('user_id', $vendorId)->first();

//     if (!$vendor) {
//         return response()->json(['message' => 'Vendor not found.'], 404);
//     }

//     // Decode services
//     $availableServices = json_decode($vendor->services, true);
//     if (empty($availableServices)) {
//         return response()->json(['message' => 'No services available for this vendor.'], 404);
//     }

//     // Retrieve pricing data
//     $pricingData = DB::table('pricing')
//         ->join('items', 'pricing.item_id', '=', 'items.id')
//         ->join('services', 'pricing.service_id', '=', 'services.id')
//         ->where('pricing.vendor_id', $vendorId)
//         ->whereIn('services.name', array_values($availableServices))
//         ->select('items.id as item_id', 'services.id as service_id', 'services.name as service_name', 'items.name as item_name', 'pricing.customer_price', 'pricing.commission')
//         ->get();

//     $kgPricingData = DB::table('clothing_counts')
//         ->where('vendor_id', $vendorId)
//         ->select('id', 'customer_price', 'vendor_price', 'per_kg_count', 'created_at', 'updated_at')
//         ->get();

//     $formattedData = [];
//     foreach ($pricingData as $data) {
//         if (!isset($formattedData[$data->service_id])) {
//             $formattedData[$data->service_id] = [
//                 'service_id' => $data->service_id,
//                 'name' => $data->service_name,
//                 'items' => [],
//             ];
//         }
//         $formattedData[$data->service_id]['items'][] = [
//             'id' => $data->item_id,
//             'name' => $data->item_name,
//             'price' => $data->customer_price,
//         ];
//     }

//     if (!$kgPricingData->isEmpty()) {
//         $formattedData['Laundry by KG'] = [
//             'service_id' => 'Laundry by KG',
//             'name' => 'Laundry by KG',
//             'items' => [],
//         ];
//         foreach ($kgPricingData as $kgData) {
//             $formattedData['Laundry by KG']['items'][] = [
//                 'id' => $kgData->id,
//                 'name' => 'Per KG',
//                 'price' => $kgData->customer_price,
//             ];
//         }
//     }

//     $userId = $vendor->user_id;
//     $userDetails = DB::table('users')
//         ->select('id', 'name', 'phone_number', 'email', 'role', 'wallet')
//         ->where('user_id', $userId)
//         ->first();

//     $vendorDetails = DB::table('vendors')
//         ->select('id', 'user_id', 'store_name', 'services', 'store_adhar', 'store_documents', 'store_pictures', 'store_selfies', 'profile_image', 'opening_hours')
//         ->where('user_id', $userId)
//         ->first();

// $decodeAndCleanImages = function ($field) {
//     // Remove unwanted slashes and quotes
//     $field = stripslashes($field);
//     $field = trim($field, '"');

//     // Decode JSON string into an array
//     $decoded = json_decode($field, true);

//     // Ensure it returns an array, even if decoding fails
//     if (is_array($decoded)) {
//         return $decoded;
//     }

//     // Handle the case where it's still a string
//     return explode(',', $field);
// };

// // Apply the function to JSON or comma-separated fields
//     $vendorDetails->services = json_decode($vendorDetails->services, true);
// $vendorDetails->store_adhar = $decodeAndCleanImages($vendorDetails->store_adhar);
// $vendorDetails->store_documents = $decodeAndCleanImages($vendorDetails->store_documents);
// $vendorDetails->store_pictures = $decodeAndCleanImages($vendorDetails->store_pictures);
// $vendorDetails->store_selfies = $decodeAndCleanImages($vendorDetails->store_selfies);
// $vendorDetails->profile_image = $decodeAndCleanImages($vendorDetails->profile_image);
    

//     $openingHours = json_decode($vendor->opening_hours, true);
//     $formattedOpeningHours = [];
//     if (!empty($openingHours)) {
//         foreach ($openingHours as $day => $timing) {
//             $formattedOpeningHours[] = [
//                 'day' => $day,
//                 'timing' => $timing,
//             ];
//         }
//     }

//     $serviceNames = array_values($vendorDetails->services);
//     $serviceIds = DB::table('services')->whereIn('name', $serviceNames)->select('id', 'name')->get();

//     $formattedServices = [];
//     foreach ($serviceIds as $service) {
//         $formattedServices[] = [
//             'id' => $service->id,
//             'name' => $service->name,
//         ];
//     }

//     return response()->json([
//         'pricing_data' => array_values($formattedData),
//         'user_details' => $userDetails,
//         'vendor_details' => array_merge((array) $vendorDetails, [
//             'services' => $formattedServices,
//             'opening_hours' => $formattedOpeningHours,
//         ]),
//     ], 200);
// }

    



    public function updatePricingData(Request $request)
    {
        $request->validate([
            'vendor_id' => 'required|exists:vendors,user_id',
            'service_name' => 'required|string',
            'item_name' => 'nullable|string',
            'customer_price' => 'nullable|numeric',
            'vendor_price' => 'nullable|numeric',
            'per_kg_count' => 'nullable|integer'
        ]);

        DB::beginTransaction();

        try {
            $vendorId = $request->vendor_id;
            $serviceName = $request->service_name;
            $itemName = $request->item_name;
            $customerPrice = $request->customer_price;
            $vendorPrice = $request->vendor_price;
            $perKgCount = $request->per_kg_count;

            if ($serviceName === 'Laundry by KG' && is_null($itemName)) {
                $updateData = array_filter([
                    'customer_price' => $customerPrice,
                    'vendor_price' => $vendorPrice,
                    'per_kg_count' => $perKgCount
                ]);

                $updated = DB::table('clothing_counts')
                    ->where('vendor_id', $vendorId)
                    ->update($updateData);
            } else {
                $service = DB::table('services')->where('name', $serviceName)->first();
                $item = DB::table('items')->where('name', $itemName)->first();

                if (!$service || !$item) {
                    return response()->json(['message' => 'Invalid service or item name provided.'], 404);
                }

                $updateData = array_filter([
                    'customer_price' => $customerPrice,
                    'vendor_price' => $vendorPrice
                ]);

                $pricingUpdated = DB::table('pricing')
                    ->where('vendor_id', $vendorId)
                    ->where('service_id', $service->id)
                    ->where('item_id', $item->id)
                    ->update($updateData);
            }

            if (($updated ?? $pricingUpdated ?? 0) === 0) {
                return response()->json(['message' => 'No matching data found to update.'], 404);
            }

            DB::commit();
            return response()->json(['message' => 'Pricing data updated successfully.'], 200);

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Error updating pricing data', ['error' => $e->getMessage()]);
            return response()->json(['message' => 'An error occurred while updating pricing data.'], 500);
        }
    }

    public function getAdminPricingData(Request $request)
    {
        $vendorId = $request->input('vendor_id');
        $vendor = DB::table('vendors')->select('services')->where('user_id', $vendorId)->first();

        if (!$vendor) {
            return response()->json(['message' => 'Vendor not found.'], 404);
        }

        $availableServices = json_decode($vendor->services, true);
        if (empty($availableServices)) {
            return response()->json(['message' => 'No services available for this vendor.'], 404);
        }

        $pricingData = DB::table('pricing')
            ->join('items', 'pricing.item_id', '=', 'items.id')
            ->join('services', 'pricing.service_id', '=', 'services.id')
            ->where('pricing.vendor_id', $vendorId)
            ->whereIn('services.name', array_values($availableServices))
            ->select('services.name as service_name', 'items.name as item_name', 'pricing.customer_price', 'pricing.vendor_price', 'pricing.commission')
            ->get();

        $kgPricingData = DB::table('clothing_counts')->where('vendor_id', $vendorId)->select('customer_price', 'vendor_price', 'per_kg_count', 'created_at', 'updated_at')->get();

        $formattedData = [];

        foreach ($pricingData as $data) {
            if (!isset($formattedData[$data->service_name])) {
                $formattedData[$data->service_name] = [
                    'items' => [],
                ];
            }
            $formattedData[$data->service_name]['items'][] = [
                'item_name' => $data->item_name,
                'customer_price' => $data->customer_price,
                'vendor_price' => $data->vendor_price,
                'commission' => $data->commission,
            ];
        }

        if (!$kgPricingData->isEmpty()) {
            $formattedData['Laundry by KG'] = [
                'items' => [],
            ];
            foreach ($kgPricingData as $kgData) {
                $formattedData['Laundry by KG']['items'][] = [
                    'per_kg_count' => $kgData->per_kg_count,
                    'customer_price' => $kgData->customer_price,
                    'vendor_price' => $kgData->vendor_price,
                ];
            }
        }

        return response()->json($formattedData, 200);
    }
}
