<?php

namespace Modules\Payment\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Payment\Services\PaymentService;

class PaymentController extends Controller
{
    protected $paymentService;

    public function __construct(PaymentService $paymentService)
    {
        $this->paymentService = $paymentService;
    }
    private function pay()
    {
        $orderId = uniqid('ORD_');

        $payment = $this->paymentService->createPayment(
            orderId: $orderId,
            amount: 100.00,
            currency: 'SAR',
            customer: [
                'name' => 'Mohamed Khedewy',
                'email' => 'khedewy@example.com',
                'phone' => '971500000000',
            ]
        );

        if (isset($payment['order']['url'])) {
            session()->put('telr_ref', $payment['order']['ref']); // Save for status check
            return redirect($payment['order']['url']);
        }

        return response()->json(['error' => $payment['error']['message'] ?? 'Failed to create payment'], 400);
    }

    public function success(Request $request)
    {
        $ref = $request->OrderRef ?? null;
        if (!$ref) {
            return 'Missing Telr Ref';
        }
        $status = $this->paymentService->checkStatus($ref);

        if (isset($status['order']['status']['code'])) {
            $code = $status['order']['status']['code'];
            $msg = $status['order']['status']['text'] ?? 'Unknown';

            if ($code == 3) {
                return "✅ Payment Successful! - {$msg}";
            } elseif ($code == 2) {
                return "⏳ Payment Pending - {$msg}";
            } else {
                return "❌ Payment Failed or Cancelled - {$msg}";
            }
        }

        return 'Error retrieving status';
    }

    public function cancel(Request $request)
    {
        $ref = $request->OrderRef ?? null;

        if (!$ref) {
            return 'Missing Telr Ref';
        }
        $payment = $this->paymentService->getItemByRef($ref);
        $this->paymentService->update([
            'status' => 'cancelled',
        ], $payment->id);
        $this->paymentService->createDetails([
            'payment_id' => $payment->id,
            'response' => $request->all() ?? null,
            'type' => 'callback'
        ]);
        return "❌ Payment was cancelled.";
    }
}
