<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class WebhookController extends Controller
{
    /**
     * Get all orders via webhook
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getAllOrders(Request $request): JsonResponse
    {
        try {
            // Validate request parameters
            $validator = Validator::make($request->all(), [
                'payment_status' => 'string|in:pending,completed,failed,refunded,0,1,2,3',
                'payment_type' => 'string',
                'date_from' => 'date',
                'date_to' => 'date|after_or_equal:date_from',
                'order_id' => 'string',
                'email' => 'email',
                'refferal_code' => 'string',
                'only_refferal_orders' => 'string|in:true,false,1,0'
            ]);
            if ($validator->fails()) {
                return $this->handleValidationFailure($validator);
            }
            // Build query
            $query = Order::with(['plan', 'user', 'coupon']);
            
            if($request->has('only_refferal_orders') && ($request->only_refferal_orders === 'true' || $request->only_refferal_orders === '1')){
                $query->whereNotNull('refferal_code')->where('refferal_code', '!=', '');
            }

            // Apply filters
            if ($request->has('payment_status')) {
                $query->where('payment_status', $this->getStatusValue($request->payment_status));
            }

            if ($request->has('payment_type')) {
                $query->where('payment_type', $request->payment_type);
            }

            if ($request->has('date_from')) {
                $query->whereDate('created_at', '>=', $request->date_from);
            }

            if ($request->has('date_to')) {
                $query->whereDate('created_at', '<=', $request->date_to);
            }

            if ($request->has('order_id')) {
                $query->where('order_id', 'like', '%' . $request->order_id . '%');
            }

            if ($request->has('email')) {
                $query->where('email', 'like', '%' . $request->email . '%');
            }
            
            if($request->has('refferal_code')) {
                $query->where('refferal_code', 'like', '%' . $request->refferal_code . '%');
            }
            // Pagination
            $perPage = $request->get('per_page', 15);
            $orders = $query->orderBy('created_at', 'desc')->paginate($perPage);
            
            // Format response
            $formattedOrders = $orders->map(function ($order) {
                return $this->formatOrder($order);
            });
            
            // Create a custom paginated response with formatted data
            return $this->withPaginationFormatted($orders, $formattedOrders, 'Orders retrieved successfully');
        } catch (\Exception $e) {
            return $this->error('Internal server error', $e->getMessage());
        }
    }

  

    /**
     * Format order data for API response
     *
     * @param Order $order
     * @param bool $includeDetails
     * @return array
     */
    private function formatOrder(Order $order, bool $includeDetails = false): array
    {
        $formatted = [
            'id' => $order->id,
            'order_id' => $order->order_id,
            'name' => $order->name,
            'email' => $order->email,
            'plan_name' => $order->plan_name,
            'plan_id' => $order->plan_id,
            'is_recurring' => $order->is_recurring,
            'price' => $order->price,
            'original_price' => $order->original_price ?? $order->price,
            'price_currency' => $order->price_curency,
            'payment_status' => $this->getStatusText($order->payment_status),
            'payment_status_code' => $order->payment_status,
            'payment_type' => $this->getPaymentStatusText($order->payment_type),
            'txn_id' => $order->txn_id,
            'coupon_code' => $order->coupon_code,
            'discount_amount' => $order->discount_amount,
            'interval' => $order->interval,
            'receipt' => $order->receipt,
            'user_id' => $order->user_id,
            'workspace' => $order->workspace,
            'is_refund' => $order->is_refund,
            'refferal_code' => $order->refferal_code,
            'created_at' => $this->formatTimestamp($order->created_at),
            'updated_at' => $this->formatTimestamp($order->updated_at),
        ];

        // Include plan details
        if ($order->plan) {
            $formatted['plan'] = [
                'id' => $order->plan->id,
                'name' => $order->plan->name,
                'description' => $order->plan->description ?? null,
                'price' => $order->plan->price ?? null,
                'interval' => $order->plan->interval ?? null,
            ];
        }

        // Include user details if requested
        if ($includeDetails && $order->user) {
            $formatted['user'] = [
                'id' => $order->user->id,
                'name' => $order->user->name ?? null,
                'email' => $order->user->email ?? null,
            ];
        }

        // Include coupon details if exists
        if ($order->coupon) {
            $formatted['coupon'] = [
                'id' => $order->coupon->id,
                'code' => $order->coupon->code,
                'discount_type' => $order->coupon->discount_type ?? null,
                'discount_value' => $order->coupon->discount_value ?? null,
            ];
        }

        // Include subscription details if exists
        if ($includeDetails && $order->subscription) {
            $formatted['subscription'] = [
                'id' => $order->subscription->id,
                'stripe_subscription_id' => $order->subscription->stripe_subscription_id ?? null,
                'status' => $order->subscription->status ?? null,
                'current_period_start' => $order->subscription->current_period_start ?? null,
                'current_period_end' => $order->subscription->current_period_end ?? null,
            ];
        }

        return $formatted;
    }

    /**
     * Get status text from status code
     *
     * @param int $status
     * @return string
     */
    private function getStatusText(int $status): string
    {
        return match ($status) {
            0 => 'pending',
            1 => 'completed',
            2 => 'failed',
            3 => 'refunded',
            default => 'unknown',
        };
    }
   

    private function getPaymentStatusText(int $status): string
    {
        return match ($status) {
            1 => 'bank',
            2 => 'pay_pal',
            3 => 'stripe',
            default => 'unknown',
        };
    }

    /**
     * Get status code from status text
     *
     * @param string $status
     * @return int
     */
    private function getStatusValue(?string $status): int
    {
        if (is_null($status)) {
            return 0; // Default to pending
        }
        return match ($status) {
            'pending', '0' => 0,
            'completed', '1' => 1,
            'failed', '2' => 2,
            'refunded', '3' => 3,
            default => 0, // Default to pending for unknown values
        };
    }

    /**
     * Format timestamp for API response
     *
     * @param mixed $timestamp
     * @return string|null
     */
    private function formatTimestamp($timestamp): ?string
    {
        if (is_null($timestamp)) {
            return null;
        }
        if (is_string($timestamp)) {
            try {
                return \Carbon\Carbon::parse($timestamp)->toISOString();
            } catch (\Exception $e) {
                return $timestamp; // Return as-is if parsing fails
            }
        }
        if (method_exists($timestamp, 'toISOString')) {
            return $timestamp->toISOString();
        }
        return (string) $timestamp;
    }
}
