<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\JewelryImport;
use App\Models\Jewelry;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use App\Models\Setting;
use App\Http\Controllers\Admin\SettingController;


class JewelryController extends Controller
{
    public function importPage()
    {
        return view('admin.jewelry.import');
    }

    public function import(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xlsx,csv'
        ]);

        Excel::import(new JewelryImport, $request->file('file'));

        return back()->with('success', '✅ Import Successful');
    }

    public function products()
    {
          $products = Jewelry::with('images')->latest()->get();

        return view('admin.product.product', compact('products'));
    }

        public function product_data()
        {
            $products = Jewelry::with('images')->get();

            $data = [];

            $extraCharge = floatval(
                Setting::where('key', 'gold_extra_charge')->value('value') ?? 0
            );

            foreach ($products as $product) {

                if ($product->images->count() > 0 && $product->images->first()->image_path) {
                    $image = '<img src="' . asset('storage/' . $product->images->first()->image_path) . '" width="80">';
                } else {
                    $image = '<img src="' . asset('public/img/no_image.jpg') . '" width="80">';
                }

                $data[] = [

                    'image' => $image,

                    'collection' => $product->collection,
                    'new_triple_sku' => $product->new_triple_sku,
                    'old_triple_sku' => $product->old_triple_sku,
                    'vendor_id' => $product->vendor_id,
                    'barcode_wg' => $product->barcode_wg,
                    'barcode_yg' => $product->barcode_yg,
                    'product_type' => $product->product_type,
                    'description' => $product->description,
                    'size' => $product->size,
                    'order_qty' => $product->order_qty,
                    'pi_status' => $product->pi_status,
                    'purchase_no' => $product->purchase_no,
                    'purchase_date' => $product->purchase_date,
                    'pcs' => $product->pcs,
                    'total_weight' => $product->total_weight,
                    'net_weight' => $product->net_weight,
                    'metal_kt' => $product->metal_kt,
                    'metal_color' => $product->metal_color,
                    'gross_weight' => $product->gross_weight,
                    'gold_lock' => $product->gold_lock,
                    'gold_rate' => $product->gold_rate,
                    'gold_value' => $product->gold_value,
                    'finding_type' => $product->finding_type,
                    'finding_qty' => $product->finding_qty,
                    'finding_weight' => $product->finding_weight,
                    'finding_rate' => $product->finding_rate,
                    'finding_value' => $product->finding_value,
                    'diamond_type' => $product->diamond_type,
                    'diamond_size' => $product->diamond_size,
                    'diamond_pcs' => $product->diamond_pcs,
                    'diamond_ct' => $product->diamond_ct,
                    'diamond_rate' => $product->diamond_rate,
                    'diamond_value' => $product->diamond_value,
                    'cfp' => $product->cfp,
                    'setting' => $product->setting,
                    'joining' => $product->joining,
                    'rhodium' => $product->rhodium,
                    'stamp' => $product->stamp,
                    'finding_charge' => $product->finding_charge,
                    'handling' => $product->handling,
                    'total_labor' => $product->total_labor,
                    'total_value' => $product->total_value,
                    'duty' => $product->duty,
                    'with_duty' => $product->with_duty,
                    'b2b_wholesaler_90' => $product->b2b_wholesaler_90,
                    'b2b_wholesaler_85' => $product->b2b_wholesaler_85,
                    'b2b_regular_82' => $product->b2b_regular_82,
                    'b2b_regular_80' => $product->b2b_regular_80,
                    'other_online_75' => $product->other_online_75,
                    'online_70' => $product->online_70,
                    'pop_selling_price' => $product->pop_selling_price,
                    'br_cost_price' => $product->br_cost_price,
                    'amazon_price' => $product->amazon_price,
                    'flyer_price' => $product->flyer_price,

                    'action' => '<a href="' . route('admin.jewelry.edit', $product->id) . '" class="btn btn-sm btn-primary"><i class="fas fa-edit"></i></a>',

                    // DATABASE VALUES ONLY
                    'goldPrice' => '$' . number_format($product->live_gold_rate, 2),
                    'MainPrice' => '$' . number_format($product->live_gold_rate * 31.1035, 2),
                    'net_weight_raw' => floatval($product->net_weight ?? 0),
                    'extra_charge' => $extraCharge,
                    'price' => '$' . number_format($product->final_price, 2),
                ];
            }

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


    // public function gold_price()
    // {
    //     $goldData = Cache::remember('gold_price_usd', 60, function () {

    //         $response = Http::get(
    //             'https://api.gold-api.com/price/XAU/USD'
    //         );

    //         if ($response->successful()) {

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

    //         return [];
    //     });

    //     $apiPrice = floatval($goldData['price'] ?? 0);
           
    //     $goldPrice = $apiPrice / 31.1035;

    //     return response()->json([

    //         'price' => number_format($goldPrice, 2),
    //         'main_price' => $apiPrice
    //     ]);
    // }

    public function gold_price()
    {

    $goldData = Cache::remember(
            'gold_price_usd',
            60,
            function () {

                $response = Http::get(
                    'https://api.gold-api.com/price/XAU/USD'
                );

                if ($response->successful()) {

                    return $response->json();
                }

                return [];
            }
        );

        // API PRICE
        $apiPrice = floatval(
            $goldData['price'] ?? 0
        );

        // PER GRAM PRICE
        $goldPrice = $apiPrice / 31.1035;

        // EXTRA CHARGE
        $settings = Setting::whereIn('key', [
            'gold_extra_charge',
            'duty_percent',
            'gold_loss_percent'
        ])->pluck('value', 'key');

        $extraCharge     = floatval($settings['gold_extra_charge'] ?? 0);
        $dutyPercent     = floatval($settings['duty_percent'] ?? 0);
        $goldLossPercent = floatval($settings['gold_loss_percent'] ?? 0);

        // ALL PRODUCTS
        $products = Jewelry::all();

        foreach($products as $product){

            $weight = floatval(
                $product->net_weight ?? 0
            );

            // FINAL PRICE
            $price = ($weight * $goldPrice) + $extraCharge + $dutyPercent + $goldLossPercent;
            $without_extra_price = ($weight * $goldPrice);

            // UPDATE DB
            $product->update([

                'live_gold_rate' => $goldPrice,

                'final_price'    => $price,
                'without_extra_price'=> round($without_extra_price,2),

            ]);
        }

              

        return response()->json([

            'success'     => true,

            'price'       => $goldPrice,

            'main_price'  => $apiPrice,

            'extraCharge' => $extraCharge

        ]);
    }

    public function edit($id)
    {
        $product = Jewelry::findOrFail($id);

        return view('admin.jewelry.edit', compact('product'));
    }

    public function update(Request $request, $id)
    {
        $product = Jewelry::findOrFail($id);

        $product->update($request->all());

        return redirect()
            ->back()
            ->with('success', 'Product Updated Successfully');
    }
   
}