<?php

namespace App\Http\Controllers\Api\V1\Order;

use App\Http\Controllers\Controller;
use App\Services\PaymentService;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class PaymentController extends Controller
{
    protected $paymentService;

    public function __construct(PaymentService $paymentService)
    {
        $this->paymentService = $paymentService;
    }

    /**
     * Process payment and convert temp bill to final
     */
    public function processPayment(Request $request, $id): JsonResponse
    {
        $order = Order::findOrFail($id);

        $validated = $request->validate([
            'payment_amount' => 'required|numeric|min:0',
            'payment_method' => 'required|in:cash,card,mobile',
            'tendered_amount' => 'nullable|numeric|min:0',
        ]);

        try {
            $result = $this->paymentService->processPaymentAndConvert(
                $order,
                $validated['payment_amount'],
                $validated['payment_method'],
                $validated['tendered_amount'] ?? null
            );

            return response()->json([
                'message' => $result['is_fully_paid']
                    ? 'Payment processed successfully. Bill converted to final.'
                    : 'Partial payment received.',
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Failed to process payment',
                'error' => $e->getMessage()
            ], 400);
        }
    }

    /**
     * Get cash register balance
     */
    public function getCashRegisterBalance(Request $request): JsonResponse
    {
        $branchId = $request->input('branch_id') ?? $request->user()->branch_id;

        if (!$branchId) {
            return response()->json(['message' => 'Branch ID is required'], 400);
        }

        $balance = $this->paymentService->getCashRegisterBalance($branchId);

        if ($balance === null) {
            return response()->json([
                'message' => 'No open cash register found',
                'balance' => 0
            ], 404);
        }

        return response()->json([
            'balance' => $balance
        ]);
    }

    /**
     * Print final bill / Get duplicate bill
     */
    public function printFinalBill($id): JsonResponse
    {
        $order = Order::with(['items.product', 'payments', 'branch'])
            ->findOrFail($id);

        if ($order->bill_type !== Order::BILL_TYPE_FINAL) {
            return response()->json([
                'message' => 'Only final bills can be printed'
            ], 400);
        }

        // Increment print count
        $order->incrementPrintCount();

        return response()->json([
            'data' => $order,
            'print_type' => $order->print_count === 1 ? 'original' : 'duplicate'
        ]);
    }
}
