<?php
// app/Controllers/WebhookController.php

namespace App\Controllers;

use App\Models\TransactionModel;
use App\Libraries\TransactionService; // <-- Import service baru

class WebhookController extends BaseController
{
    public function handlePayment()
    {
        $payload = $this->request->getJSON();
        $invoiceNumber = $payload->invoice_number ?? null;
        $status = $payload->status ?? null;
        
        if (!$invoiceNumber || !$status) {
            return $this->response->setStatusCode(400, 'Bad Request: Missing required payload data.');
        }
        
        // --- LOGIKA BARU YANG LEBIH BERSIH ---
        
        // Hanya proses jika statusnya adalah status sukses ('paid', 'completed', dll.)
        $successStatuses = ['paid', 'settlement', 'completed']; 
        if (!in_array($status, $successStatuses)) {
            return $this->response->setStatusCode(200, 'OK: Status not relevant.');
        }

        $transactionModel = new TransactionModel();
        $transaction = $transactionModel->where('invoice_number', $invoiceNumber)->first();
        
        if (!$transaction) {
            return $this->response->setStatusCode(404, 'Not Found: Invoice number not found.');
        }

        // Panggil service untuk melakukan semua pekerjaan
        $transactionService = new TransactionService();
        $success = $transactionService->markAsPaid($transaction->id);
        
        if (!$success) {
            return $this->response->setStatusCode(500, 'Internal Server Error during processing.');
        }
        
        return $this->response->setStatusCode(200, 'OK');
    }
}