<?php

namespace App\Http\Controllers\Api;

use App\Events\OrderPlaced;
use App\Http\Controllers\Controller;
use App\Services\CheckoutService;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;

class CheckoutController extends Controller
{
    use ApiResponse;

    protected $checkoutService;

    public function __construct(CheckoutService $checkoutService)
    {
        $this->checkoutService = $checkoutService;
    }

    public function store(Request $request)
    {
        try {
            $data = json_decode($request->input('data'), true);

            if (!$data) {
                throw new \Exception("Invalid order data format");
            }

            $order = $this->checkoutService->execute(
                $data,
                $request->file('payment_proof_file')
            );

            broadcast(new OrderPlaced($order))->toOthers();

            return $this->successResponse([
            'order_id' => $order->uuid, 
            'order_number' => $order->order_number
            ], 'Process checkout successfully');

        } catch (\Exception $e) {
            return $this->errorResponse('Failed to process checkout', 400, $e->getMessage());
        }
    }
}
