<?php

namespace App\Controllers\API;

use App\Controllers\BaseController;
use App\Models\PaymentModel;
use App\Libraries\ResponseFormatter;

class PaymentController extends BaseController
{
    protected $paymentModel;
    protected $db;
    public function __construct()
    {
        $this->paymentModel = new PaymentModel();
    }

    // 📌 CREATE PAYMENT
   public function create()
{
    $input = $this->request->getJSON(true);

    $this->db = \Config\Database::connect();
    $this->db->transBegin();

    try {

        // 🔹 insert payment
        $this->paymentModel->insert([
            'order_id' => $input['order_id'],
            'amount'   => $input['amount'],
            'method'   => $input['method'],
        ]);

        // 🔹 update order jadi paid
        $this->db->table('orders')
            ->where('id', $input['order_id'])
            ->update([
                'payment_status' => 'paid'
            ]);

        if ($this->db->transStatus() === false) {
            throw new \Exception('Gagal pembayaran');
        }

        $this->db->transCommit();

        return $this->response->setJSON(
            ResponseFormatter::success(null, 'Pembayaran berhasil')
        );

    } catch (\Exception $e) {

        $this->db->transRollback();

        return $this->response->setJSON(
            ResponseFormatter::error($e->getMessage())
        );
    }
}
}