<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TransactionController extends Controller
{
    public function index()
    {
        $transactions = Transaction::with('details')
            ->orderBy('transaction_date', 'desc')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $transactions,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'customer_name' => [
                'nullable',
                'string',
                'max:150',
            ],
            'payment_status' => [
                'required',
                'in:paid,debt,partial',
            ],
            'paid_amount' => [
                'required',
                'integer',
                'min:0',
            ],
            'items' => [
                'required',
                'array',
                'min:1',
            ],
            'items.*.product_id' => [
                'required',
                'integer',
                'exists:products,id',
            ],
            'items.*.quantity' => [
                'required',
                'integer',
                'min:1',
            ],
        ]);

        try {
            $transaction = DB::transaction(function () use ($validated) {

                $total = 0;
                $details = [];

                foreach ($validated['items'] as $item) {

                    $product = Product::find(
                        $item['product_id']
                    );

                    if ($product->stock < $item['quantity']) {
                        throw new \Exception(
                            "Stok {$product->name} tidak mencukupi."
                        );
                    }

                    $subtotal =
                        $product->price *
                        $item['quantity'];

                    $total += $subtotal;

                    $details[] = [
                        'product' => $product,
                        'quantity' => $item['quantity'],
                        'subtotal' => $subtotal,
                    ];
                }

                $paidAmount =
                    $validated['paid_amount'];

                if ($paidAmount > $total) {
                    $changeAmount =
                        $paidAmount - $total;
                } else {
                    $changeAmount = 0;
                }

                $invoiceNumber = 'TRX-' .now()->format('YmdHis');

                $transaction = Transaction::create([
                                'invoice_number' =>
                                    $invoiceNumber,

                                'transaction_date' =>
                                    now(),

                                'customer_name' =>
                                    $validated['customer_name']
                                    ?? null,

                                'payment_status' =>
                                    $validated['payment_status'],

                                'total' =>
                                    $total,

                                'paid_amount' =>
                                    $paidAmount,

                                'change_amount' =>
                                    $changeAmount,
                            ]);

                foreach ($details as $detail) {

                    $product = $detail['product'];

                    $transaction->details()->create([
                        'product_id' =>
                            $product->id,

                        'product_name' =>
                            $product->name,

                        'price' =>
                            $product->price,

                        'quantity' =>
                            $detail['quantity'],

                        'subtotal' =>
                            $detail['subtotal'],
                    ]);

                    $product->decrement(
                        'stock',
                        $detail['quantity']
                    );
                }

                return $transaction;
            });

            $transaction->load('details');

            return response()->json([
                'success' => true,
                'message' =>
                    'Transaksi berhasil disimpan',

                'data' => $transaction,
            ], 201);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 422);
        }
    }

    public function show($id)
    {
        $transaction = Transaction::with(['details','debtPayments'])->find($id);

        if (!$transaction) {
            return response()->json([
                'success' => false,
                'message' => 'Transaksi tidak ditemukan',
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $transaction,
        ]);
    }
}