<?php

declare(strict_types=1);
namespace Controllers;

use Helpers\Request;
use Helpers\Response;
use Services\RazorpayService;
use Services\OrderService;
use Validators\Validator;

final class PaymentController
{
    public function createRazorpayOrder(): never
    {
        try { \Helpers\Auth::requireUser(); } catch (\Throwable $e) { Response::error('Authentication required before checkout', 401); }
        $data = Request::input();
        $errors = Validator::validate($data, [
            'customer_name' => 'required|min:2',
            'customer_phone' => 'required|min:10',
            'address_line1' => 'required',
            'city' => 'required',
            'state' => 'required',
            'pincode' => 'required',
            'items' => 'required|array'
        ]);
        if ($errors) Response::error('Validation failed', 422, $errors);
        try {
            $orderService = new OrderService();
            $pending = $orderService->createPendingOnline($data);
            $rzp = (new RazorpayService())->createOrder((float)$pending['total_amount'], $pending['order_number']);
            if (!empty($rzp['id'])) {
                $orderService->attachRazorpayOrderId($pending['order_number'], $rzp['id']);
            }
            Response::success(['local_order' => $pending, 'razorpay_order' => $rzp]);
        } catch (\Throwable $e) {
            Response::error($e->getMessage(), 400);
        }
    }

    public function verify(): never
    {
        $data = Request::input();
        $errors = Validator::validate($data, [
            'order_number' => 'required',
            'razorpay_order_id' => 'required',
            'razorpay_payment_id' => 'required',
            'razorpay_signature' => 'required'
        ]);
        if ($errors) Response::error('Validation failed', 422, $errors);
        try {
            $razorpay = new RazorpayService();
            $valid = $razorpay->verifySignature($data['razorpay_order_id'], $data['razorpay_payment_id'], $data['razorpay_signature']);
            if (!$valid) Response::error('Payment signature verification failed', 400);
            $payment = $razorpay->fetchPayment((string)$data['razorpay_payment_id']);
            if (($payment['order_id'] ?? '') !== $data['razorpay_order_id']) Response::error('Payment does not belong to this Razorpay order', 400);
            $allowedStatuses = ['captured', 'authorized'];
if (!in_array($payment['status'] ?? '', $allowedStatuses, true)) {
    Response::error('Payment is not captured', 400);
}
            $paidAmount = ((float)($payment['amount'] ?? 0)) / 100;
            (new OrderService())->markPaid((string)$data['order_number'], (string)$data['razorpay_order_id'], (string)$data['razorpay_payment_id'], $paidAmount, (string)$data['razorpay_signature'], $payment);
            Response::success(['order_number' => $data['order_number']], 'Payment verified');
        } catch (\Throwable $e) {
            Response::error($e->getMessage(), 400);
        }
    }

    public function failed(): never
    {
        $data = Request::input();
        if (empty($data['order_number'])) Response::error('Order number is required', 422);
        (new OrderService())->markFailed((string)$data['order_number']);
        Response::success([], 'Payment marked failed');
    }
}
