<?php
defined('BASEPATH') or exit('No direct script access allowed');

require_once APPPATH . 'third_party/midtrans/Midtrans.php';

class Midtransservice
{

    private $ci;

    public function __construct()
    {
        $this->ci = &get_instance();
        $this->ci->config->load('midtrans');

        // Set Midtrans configuration
        \Midtrans\Config::$serverKey = $this->ci->config->item('server_key', 'midtrans');
        \Midtrans\Config::$clientKey = $this->ci->config->item('client_key', 'midtrans');
        \Midtrans\Config::$isProduction = $this->ci->config->item('is_production', 'midtrans');
        \Midtrans\Config::$isSanitized = true;
        \Midtrans\Config::$is3ds = true;
    }

    /**
     * Create Snap Token for payment
     */
    public function createSnapToken($transaction_details, $customer_details = null, $item_details = null)
    {
        $params = array(
            'transaction_details' => $transaction_details,
            'customer_details' => $customer_details,
            'item_details' => $item_details,
            'enabled_payments' => $this->ci->config->item('payment_settings', 'midtrans')['enabled_payments'],
            'expiry' => $this->ci->config->item('payment_settings', 'midtrans')['expiry']
        );

        try {
            $snapToken = \Midtrans\Snap::getSnapToken($params);
            return $snapToken;
        } catch (Exception $e) {
            log_message('error', 'Midtrans Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Handle notification/webhook
     */
    public function handleNotification()
    {
        try {
            $notification = new \Midtrans\Notification();
            return $notification;
        } catch (Exception $e) {
            log_message('error', 'Midtrans Notification Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Get transaction status
     */
    public function getStatus($order_id)
    {
        try {
            $status = \Midtrans\Transaction::status($order_id);
            return $status;
        } catch (Exception $e) {
            log_message('error', 'Midtrans Status Error: ' . $e->getMessage());
            return false;
        }
    }
}
