<?php

namespace App\Controllers\Api;

use CodeIgniter\RESTful\ResourceController;
use App\Models\PaymentModel;
use App\Models\ActivityLogModel;

class PaymentApi extends ResourceController
{
    public function create()
    {
        $input = $this->request->getJSON();
        $db = \Config\Database::connect();
        $db->transStart(); // Mulai transaksi database agar aman

        $paymentModel = new PaymentModel();
        
        // Validasi
        if (empty($input->id_order) || empty($input->total)) {
            return $this->fail('Data pembayaran tidak lengkap', 400);
        }

        $paymentModel->save([
            'id_order'           => $input->id_order,
            'id_payment_method'  => 1, // Default metode
            'jumlah_bayar'       => $input->total,
            'status'             => 'verified'
        ]);

        // Catat ke finance_transactions (Laba Rugi)
        $db->table('finance_transactions')->insert([
            'type'        => 'income',
            'amount'      => $input->total,
            'description' => "Pembayaran via API - Order #{$input->id_order}"
        ]);

        $db->transComplete(); // Selesaikan transaksi

        if ($db->transStatus() === false) {
            return $this->fail('Gagal menyimpan transaksi', 500);
        }

        return $this->respondCreated(['status' => 201, 'message' => 'Pembayaran dicatat']);
    }
}