<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    // COD — mark payment pending, fulfilled on delivery
    public function cod(Request $request)
    {
        $request->validate(['order_id'=>'required|exists:orders,id']);
        $order = $request->user()->orders()->findOrFail($request->order_id);
        $order->update(['status'=>Order::STATUS_CONFIRMED,'payment_status'=>Order::PAYMENT_PENDING]);
        return response()->json(['success'=>true,'message'=>'COD order confirmed!','order'=>$order]);
    }

    // bKash — initiate payment
    public function bkashInit(Request $request)
    {
        $request->validate(['order_id'=>'required|exists:orders,id']);
        // TODO: Integrate bKash Tokenized API
        // $response = BkashService::createPayment($order->total, $order->order_number);
        return response()->json(['success'=>true,'payment_url'=>'https://bkash.com/payment/...','message'=>'Redirect user to bKash']);
    }

    // bKash callback (webhook)
    public function bkashCallback(Request $request)
    {
        // TODO: Verify bKash payment signature & update order
        $order = Order::where('order_number',$request->merchantInvoiceNumber)->first();
        if($order && $request->transactionStatus === 'Completed'){
            $order->update(['payment_status'=>Order::PAYMENT_PAID,'status'=>Order::STATUS_CONFIRMED,'transaction_id'=>$request->trxID]);
        }
        return response()->json(['success'=>true]);
    }

    // SSLCommerz — initiate
    public function sslInit(Request $request)
    {
        $request->validate(['order_id'=>'required|exists:orders,id']);
        // TODO: Integrate SSLCommerz PHP SDK
        return response()->json(['success'=>true,'payment_url'=>'https://securepay.sslcommerz.com/...']);
    }

    public function sslSuccess(Request $request) { return $this->handleSsl($request,'paid','confirmed'); }
    public function sslFail(Request $request)    { return $this->handleSsl($request,'failed','pending'); }
    public function sslIpn(Request $request)     { return $this->handleSsl($request,'paid','confirmed'); }

    private function handleSsl(Request $request, string $payStatus, string $status)
    {
        $order = Order::where('order_number',$request->tran_id)->first();
        if($order) $order->update(['payment_status'=>$payStatus,'status'=>$status,'transaction_id'=>$request->bank_tran_id]);
        return response()->json(['success'=>true]);
    }
}
