<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Shipping;
use App\Models\Coupon;

use App\Services\ShiprocketService;


class ShippingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $shipping=Shipping::orderBy('id','DESC')->paginate(10);
        return view('backend.shipping.index')->with('shippings',$shipping);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('backend.shipping.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'type'=>'string|required',
            'price'=>'nullable|numeric',
            'status'=>'required|in:active,inactive'
        ]);
        $data=$request->all();
        // return $data;
        $status=Shipping::create($data);
        if($status){
            request()->session()->flash('success','Shipping successfully created');
        }
        else{
            request()->session()->flash('error','Error, Please try again');
        }
        return redirect()->route('shipping.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $shipping=Shipping::find($id);
        if(!$shipping){
            request()->session()->flash('error','Shipping not found');
        }
        return view('backend.shipping.edit')->with('shipping',$shipping);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $shipping=Shipping::find($id);
        $this->validate($request,[
            'type'=>'string|required',
            'price'=>'nullable|numeric',
            'status'=>'required|in:active,inactive'
        ]);
        $data=$request->all();
        // return $data;
        $status=$shipping->fill($data)->save();
        if($status){
            request()->session()->flash('success','Shipping successfully updated');
        }
        else{
            request()->session()->flash('error','Error, Please try again');
        }
        return redirect()->route('shipping.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $shipping=Shipping::find($id);
        if($shipping){
            $status=$shipping->delete();
            if($status){
                request()->session()->flash('success','Shipping successfully deleted');
            }
            else{
                request()->session()->flash('error','Error, Please try again');
            }
            return redirect()->route('shipping.index');
        }
        else{
            request()->session()->flash('error','Shipping not found');
            return redirect()->back();
        }
    }

public function checkDelivery(Request $request)
{
    $request->validate([
        'pincode' => 'required|digits:6'
    ]);

    try {
        $shiprocket = app(\App\Services\ShiprocketService::class);

        $rates = $shiprocket->getRates(
            $request->pincode,
            0.5,   // default weight for single product page
            false  // prepaid
        );

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

    } catch (\Exception $e) {
        return response()->json([
            'status' => false,
            'error' => $e->getMessage()
        ]);
    }
}
public function testShiprocketToken()
{
    try {

        $shiprocket = new \App\Services\ShiprocketService();

        $token = $shiprocket->getToken();

        return response()->json([
            'success' => true,
            'token' => $token
        ]);

    } catch (\Exception $e) {

        return response()->json([
            'success' => false,
            'error' => $e->getMessage()
        ]);

    }
}   

public function getLiveRates(Request $request)
{
    \Log::info("STEP 1: Shipping API called", $request->all());

    $request->validate([
        'pincode' => 'required|digits:6'
    ]);

    $cod = $request->cod ?? false;

    try {

        \Log::info("STEP 2: COD value", ['cod'=>$cod]);

        $shiprocket = app(\App\Services\ShiprocketService::class);

        \Log::info("STEP 3: Calling Shiprocket service");

        $rates = $shiprocket->getRates(
            $request->pincode,
            0.5,
            $cod
        );

        \Log::info("STEP 4: Shiprocket raw response", $rates);

        if (!isset($rates['data']['available_courier_companies'])) {

            \Log::warning("STEP 5: No courier companies returned");

            return response()->json([
                'status' => false,
                'options' => []
            ]);
        }

        $options = collect($rates['data']['available_courier_companies'])
            ->map(function ($c) {

                return [
                    'courier' => $c['courier_name'] ?? '',
                    'rate' => $c['rate'] ?? 0,
                    'courier_company_id' => $c['courier_company_id'] ?? null,
                    'eta' => $c['estimated_delivery_days'] ?? ''
                ];

            })->values();

        \Log::info("STEP 6: Formatted options", $options->toArray());

        return response()->json([
            'status' => true,
            'options' => $options
        ]);

    } catch (\Exception $e) {

        \Log::error("STEP ERROR: ".$e->getMessage());

        return response()->json([
            'status' => false,
            'options' => []
        ]);
    }
}



}
