<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class CourierSettingsController extends Controller
{
    private function getSiteSettings(int $tenantId): ?object
    {
        return DB::table('site_settings')->where('tenant_id', $tenantId)->first();
    }

    /** GET /api/admin/courier-settings[?action=webhook|stats] */
    public function show(Request $request): JsonResponse
    {
        $tenant  = app('tenant');
        $ss      = $this->getSiteSettings($tenant->id);
        $action  = $request->query('action');

        if ($action === 'webhook') {
            $token = $ss?->courier_webhook_token ?: Str::random(32);
            // Ensure token is saved
            if (!$ss?->courier_webhook_token) {
                DB::table('site_settings')->where('tenant_id', $tenant->id)
                    ->update(['courier_webhook_token' => $token]);
            }
            return response()->json([
                'success' => true,
                'data'    => [
                    'webhook_url'   => url('/api/courier/webhook/' . $tenant->business_slug),
                    'webhook_token' => $token,
                ]
            ]);
        }

        if ($action === 'stats') {
            try {
                $tid   = $tenant->id;
                $cols  = \Illuminate\Support\Facades\Schema::getColumnListing('orders');

                $total   = DB::table('orders')->where('tenant_id', $tid)->count();

                // Only query courier_status if the column exists
                $delivered = in_array('courier_status', $cols)
                    ? DB::table('orders')->where('tenant_id', $tid)->where('courier_status', 'delivered')->count()
                    : 0;

                // Only query label_generated if the column exists
                $withLabels = in_array('label_generated', $cols)
                    ? DB::table('orders')->where('tenant_id', $tid)->where('label_generated', 1)->count()
                    : 0;

                $stats = [
                    'total_orders' => $total,
                    'delivered'    => $delivered,
                    'pending'      => DB::table('orders')->where('tenant_id', $tid)->where('status', 'pending')->count(),
                    'today'        => DB::table('orders')->where('tenant_id', $tid)->whereDate('created_at', today())->count(),
                    'this_week'    => DB::table('orders')->where('tenant_id', $tid)->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count(),
                    'this_month'   => DB::table('orders')->where('tenant_id', $tid)->whereMonth('created_at', now()->month)->count(),
                    'with_labels'  => $withLabels,
                    'success_rate' => $total > 0 ? round(($delivered / $total) * 100) : 0,
                ];

                return response()->json(['success' => true, 'data' => $stats]);
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'error' => 'Stats query failed: ' . $e->getMessage()], 500);
            }
        }

        // Default: return settings (never expose encrypted keys as plain text)
        return response()->json([
            'success' => true,
            'data'    => [
                'has_api_keys'     => !empty($ss?->courier_api_key),
                'api_key'          => '',   // masked for security
                'secret_key'       => '',   // masked for security
                'webhook_token'    => $ss?->courier_webhook_token ?? '',
                'business_name'    => $ss?->courier_business_name  ?? ($tenant->business_name ?? ''),
                'business_phone'   => $ss?->courier_business_phone  ?? ($tenant->phone ?? ''),
                'business_address' => $ss?->courier_business_address ?? '',
                'business_email'   => $ss?->courier_business_email  ?? ($tenant->email ?? ''),
                'status'           => 1,
            ]
        ]);
    }

    /** POST /api/admin/courier-settings[?action=test|reset] */
    public function update(Request $request): JsonResponse
    {
        $tenant = app('tenant');
        $action = $request->query('action');

        if ($action === 'test') {
            $apiKey = $request->input('api_key');
            $secret = $request->input('secret_key');
            if (!$apiKey || !$secret) {
                return response()->json(['success' => false, 'error' => 'API Key and Secret Key required'], 422);
            }
            try {
                $res = \Illuminate\Support\Facades\Http::withHeaders([
                    'Api-Key'    => $apiKey,
                    'Secret-Key' => $secret,
                    'Accept'     => 'application/json',
                ])->get('https://portal.steadfast.com.bd/api/v1/get_balance');

                if ($res->successful() && isset($res['current_balance'])) {
                    return response()->json([
                        'success' => true,
                        'message' => 'SteadFast API connected successfully!',
                        'balance' => $res['current_balance']
                    ]);
                }
            } catch (\Exception $e) {
                // fall through
            }
            return response()->json(['success' => false, 'error' => 'Connection failed. Check your credentials.']);
        }

        if ($action === 'reset') {
            DB::table('site_settings')->where('tenant_id', $tenant->id)->update([
                'courier_api_key'          => null,
                'courier_secret_key'       => null,
                'courier_webhook_token'    => null,
                'courier_business_name'    => null,
                'courier_business_phone'   => null,
                'courier_business_address' => null,
                'courier_business_email'   => null,
            ]);
            return response()->json(['success' => true, 'message' => 'Courier settings reset successfully.']);
        }

        // Default: save settings
        $update = [
            'courier_business_name'    => $request->input('business_name'),
            'courier_business_phone'   => $request->input('business_phone'),
            'courier_business_address' => $request->input('business_address'),
            'courier_business_email'   => $request->input('business_email'),
        ];

        if ($request->filled('api_key'))    $update['courier_api_key']    = $request->input('api_key');
        if ($request->filled('secret_key')) $update['courier_secret_key'] = $request->input('secret_key');

        // Generate webhook token if not exists
        $existing = $this->getSiteSettings($tenant->id);
        if (!$existing?->courier_webhook_token) {
            $update['courier_webhook_token'] = Str::random(32);
        }

        DB::table('site_settings')->where('tenant_id', $tenant->id)->update($update);

        return response()->json([
            'success' => true,
            'message' => 'Courier settings saved successfully!',
            'data'    => ['has_api_keys' => true],
        ]);
    }
}
