<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Payment;
use App\Models\SupplierTransaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class PaymentController extends Controller
{
    public function initiateCardPayment(Request $request)
    {
        $user = auth()->user();
        $company = $user->company;

        if (!$company) {
            return response()->json(['error' => 'Company profile not found'], 404);
        }

        $validator = Validator::make($request->all(), [
            'order_id' => 'required|exists:orders,id',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $order = Order::where('company_id', $company->id)
            ->where('id', $request->order_id)
            ->where('payment_status', 'pending')
            ->firstOrFail();

        $payment = Payment::create([
            'order_id' => $order->id,
            'amount' => $order->total_amount,
            'method' => 'card',
            'status' => 'processing',
            'reference' => Payment::generateReference(),
        ]);

        return response()->json([
            'message' => 'Card payment initiated',
            'payment' => $payment,
            'redirect_url' => '/payment/card/' . $payment->reference,
        ]);
    }

    public function initiateOzowPayment(Request $request)
    {
        $user = auth()->user();
        $company = $user->company;

        if (!$company) {
            return response()->json(['error' => 'Company profile not found'], 404);
        }

        $validator = Validator::make($request->all(), [
            'order_id' => 'required|exists:orders,id',
            'bank_id' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $order = Order::where('company_id', $company->id)
            ->where('id', $request->order_id)
            ->where('payment_status', 'pending')
            ->firstOrFail();

        $payment = Payment::create([
            'order_id' => $order->id,
            'amount' => $order->total_amount,
            'method' => 'ozow',
            'status' => 'processing',
            'reference' => Payment::generateReference(),
        ]);

        $ozowPaymentUrl = $this->generateOzowPaymentUrl($payment, $order, $company);

        return response()->json([
            'message' => 'Ozow payment initiated',
            'payment' => $payment,
            'redirect_url' => $ozowPaymentUrl,
        ]);
    }

    private function generateOzowPaymentUrl($payment, $order, $company)
    {
        return '/payment/ozow/' . $payment->reference;
    }

    public function confirmPayment(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'reference' => 'required|string',
            'transaction_id' => 'required|string',
            'status' => 'required|in:completed,failed',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $payment = Payment::where('reference', $request->reference)->firstOrFail();

        if ($payment->status !== 'processing') {
            return response()->json(['error' => 'Payment already processed'], 422);
        }

        DB::beginTransaction();

        try {
            $payment->update([
                'status' => $request->status,
                'transaction_id' => $request->transaction_id,
                'gateway_response' => json_encode($request->all()),
            ]);

            $order = $payment->order;

            if ($request->status === 'completed') {
                $order->update([
                    'payment_status' => 'paid',
                    'status' => 'confirmed',
                ]);

                $this->createSupplierTransactions($order);
            } else {
                $order->update(['payment_status' => 'failed']);
            }

            DB::commit();

            return response()->json([
                'message' => 'Payment ' . $request->status,
                'payment' => $payment,
                'order' => $order,
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['error' => 'Failed to process payment'], 500);
        }
    }

    public function confirm30DaysPayment(Request $request)
    {
        $user = auth()->user();
        $company = $user->company;

        if (!$company) {
            return response()->json(['error' => 'Company profile not found'], 404);
        }

        $validator = Validator::make($request->all(), [
            'order_id' => 'required|exists:orders,id',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $order = Order::where('company_id', $company->id)
            ->where('id', $request->order_id)
            ->where('payment_method', '30_days')
            ->where('payment_status', 'pending')
            ->firstOrFail();

        DB::beginTransaction();

        try {
            $order->update(['status' => 'confirmed']);

            $this->createSupplierTransactions($order);

            DB::commit();

            return response()->json([
                'message' => 'Order confirmed with 30-day payment terms',
                'order' => $order,
                'invoice_due_date' => $order->invoice_due_date,
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['error' => 'Failed to confirm order'], 500);
        }
    }

    private function createSupplierTransactions($order)
    {
        $orderItems = $order->items()->with('supplier')->get();

        $supplierTotals = $orderItems->groupBy('supplier_id')->map(function ($items) {
            return [
                'supplier' => $items->first()->supplier,
                'total' => $items->sum('total_price'),
            ];
        });

        foreach ($supplierTotals as $supplierId => $data) {
            $supplier = $data['supplier'];
            $amount = $data['total'];
            $commission = round($amount * ($supplier->commission_rate / 100), 2);
            $netAmount = $amount - $commission;

            SupplierTransaction::create([
                'supplier_id' => $supplierId,
                'order_id' => $order->id,
                'transaction_type' => 'sale',
                'description' => "Sale from order {$order->order_number}",
                'amount' => $amount,
                'commission' => $commission,
                'net_amount' => $netAmount,
                'status' => 'pending',
            ]);
        }
    }

    public function paymentStatus($reference)
    {
        $payment = Payment::where('reference', $reference)
            ->with('order')
            ->firstOrFail();

        return response()->json($payment);
    }
}
