<?php

namespace App\Http\Controllers\Admin;

use App\Models\Courier;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\CourierApi as ModelsCourierApi;
use App\Services\CourierApi;
use Illuminate\Support\Facades\Http;

class CourierController extends Controller
{
    public function index()
    {
        $courier = Courier::orderBy('id', 'desc')->paginate(50);
        return response()->json([
            'status' => 'SUCCESS',
            'couriers' => $courier
        ]);
    }



    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:couriers',
        ]);

        $courier = new Courier();
        $courier->name = $request->name;
        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('images/courier', 'public');
            $courier->image = $path;
        }
        $courier->save();
        return response()->json([
            'status' => 'SUCCESS',
            'message' => "courier add successfully"
        ]);
    }


    public function edit($id)
    {
        $courier = Courier::findOrFail($id);

        return response()->json([
            'status' => 'SUCCESS',
            'courier' => $courier
        ]);
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required',
        ]);

        $courier = courier::findOrFail($id);

        $courier->name = $request->name;
        if ($request->hasFile('image')) {
            $path = $request->file('image')->store('images/courier', 'public');
            $courier->image = $path;
        }
        $courier->save();
        return response()->json([
            'status' => 'SUCCESS',
            'message' => " Updated successfully"
        ]);
    }



    public function active($id)
    {
        $courier = courier::findOrFail($id);
        $courier->status = 1;
        $courier->save();
        return response()->json([
            'status' => 'SUCCESS',
            'message' => 'courier active successfully'
        ]);
    }

    public function deActive($id)
    {
        $courier = courier::findOrFail($id);

        $courier->status = 0;
        $courier->save();
        return response()->json([
            'status' => 'SUCCESS',
            'message' => 'courier de-active successfully'
        ]);
    }



    public function search_courier($data)
    {
        $couriers = Courier::where('name', 'like', '%' . $data . '%')->paginate(20);
        return response()->json(['couriers' => $couriers]);
    }


    public function couriers()
    {
        $couriers = Courier::orderBy('id', 'desc')->where('status', 1)->get();
        return response()->json([
            'status' => true,
            'couriers' => $couriers
        ]);
    }


    public function setDefault($id)
    {
        $courier = Courier::findOrFail($id);
        $courier->activate();
        return response()->json([
            'status' => true,
            'message' => 'Set Default',
        ]);
    }



    public function generatePathaoToken()
    {
        try {

            $access_token = (new CourierApi())->pathaoAccessToken();

            if (!$access_token) {
                throw new \Exception('Failed to generate access token');
            }

            $data['pathao_access_token'] = $access_token;

            ModelsCourierApi::where('id', 1)->update($data);

            return response()->json([
                'status' => true,
                'message' => 'Access token generated successfully',
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'status' => false,
                'message' => 'Failed to generate access token, Given credentials are invalid',
            ], 500);
        }
    }


    public function getCourierApiInfo()
    {

        $information = ModelsCourierApi::first();
        return response()->json([
            'status' => true,
            'information' => $information
        ]);
    }





    public function  updateCourierApiInfo(Request $request)
    {

        $data = $request->validate([
            'steadfast_base_url' => 'nullable',
            'steadfast_api_key' => 'nullable',
            'steadfast_secret_key' => 'nullable',
            'redx_base_url' => 'nullable',
            'redx_store_id' => 'nullable',
            'redx_access_token' => 'nullable',
            'pathao_base_url' => 'nullable',
            'pathao_client_id' => 'nullable',
            'pathao_store_id' => 'nullable',
            'pathao_client_secret' => 'nullable',
            'pathao_client_email' => 'nullable',
            'pathao_client_password' => 'nullable',
            'pathao_access_token' => 'nullable',
            'paperfly_base_url' => 'nullable',
            'paperfly_username' => 'nullable',
            'paperfly_password' => 'nullable',
            'paperfly_api_key' => 'nullable',

        ]);

        $courier = ModelsCourierApi::first();
        if ($courier) {
            $courier->update($data);
        } else {
            $courier = ModelsCourierApi::create($data);
        }
        if ($courier->redx_without_area_entry == 0 && !empty($courier->redx_access_token)) {
            $this->redxSubscribeForNoAreaParcel($courier->redx_access_token, $courier);
        }
        return response()->json([
            'status' => true,
            'message' => 'information updated',
        ]);
    }
    public function redxSubscribeForNoAreaParcel($access_token, $courier)
    {

        $resp =    Http::withHeaders([
            'API-ACCESS-TOKEN' => 'Bearer ' . $access_token,
            'Content-Type' => 'application/json'
        ])->post('https://openapi.redx.com.bd/v1.0.0-beta/no-area-parcels/subscribe');


        if (!empty($resp) && $resp['message'] == 'Subscribed successfully!' && !$resp['isError']) {
            $courier->update(['redx_without_area_entry' => 1]);
        }
    }
}
