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

// We extend the base App_gateway class
class Xendit_gateway extends App_gateway
{
    private $api_endpoint = 'https://api.xendit.co/v2/invoices';

    public function __construct()
    {
        parent::__construct();
        $this->setId('xendit');
        $this->setName('Xendit');
        $this->setSettings([
            [
                'name'      => 'api_key',
                'encrypted' => true,
                'label'     => 'Xendit API Key',
            ],
            [
                'name'  => 'callback_token',
                'label' => 'Xendit Callback Verification Token',
            ],
            [
                'name'          => 'currencies',
                'label'         => 'settings_paymentmethod_currencies',
                'default_value' => 'IDR',
            ],
             [
                'name'          => 'description_dashboard',
                'label'         => 'settings_paymentmethod_description',
                'default_value' => 'Bayar via Kartu Kredit / Virtual Account / QRIS',
                'type'          => 'textarea',
            ]
        ]);
    }

    /**
     * Process the payment
     *
     * @param array $data
     * @return void
     */
    public function process_payment($data)
    {
        $api_key = $this->decryptSetting('api_key');

        if (empty($api_key)) {
            set_alert('danger', 'Xendit API Key not configured.');
            redirect(site_url('invoice/' . $data['invoice']->id . '/' . $data['invoice']->hash));
        }

        // --- FIX #3: ROBUST METHOD TO GET CUSTOMER CONTACT DATA ---
        $this->ci->load->model('clients_model');
        $contact = $this->ci->clients_model->get_contact(get_primary_contact_user_id($data['invoice']->clientid));

        // Validate that we have a contact and the contact has an email.
        if (!$contact || empty($contact->email)) {
            set_alert('danger', 'Pembayaran Xendit Gagal: Email untuk Kontak Utama klien ini tidak terdaftar. Mohon periksa data di menu Customers > Contacts.');
            redirect(site_url('invoice/' . $data['invoice']->id . '/' . $data['invoice']->hash));
            return; // Stop execution
        }

        $amount = (int) $data['amount'];
        $phoneNumber = preg_replace('/[^0-9]/', '', $contact->phonenumber);
        $customerName = trim($contact->firstname . ' ' . $contact->lastname);
        // Fallback to company name if contact name is empty
        if ($customerName === '') {
            $customerName = $data['invoice']->client->company;
        }

        $payload = [
            'external_id'          => 'perfex_inv_' . $data['invoice']->id . '_' . time(),
            'amount'               => $amount,
            'payer_email'          => $contact->email, // Use email from Primary Contact
            'description'          => 'Payment for Invoice ' . format_invoice_number($data['invoice']->id),
            'success_redirect_url' => site_url('invoice/' . $data['invoice']->id . '/' . $data['invoice']->hash),
            'failure_redirect_url' => site_url('invoice/' . $data['invoice']->id . '/' . $data['invoice']->hash),
            'customer'             => [
                'given_names'   => $customerName, // Use name from Primary Contact
                'email'         => $contact->email, // Use email from Primary Contact
                'mobile_number' => $phoneNumber, // Use phone from Primary Contact
            ],
            'currency'             => $data['invoice']->currency_name,
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->api_endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_USERPWD, $api_key . ':');
        $headers = ['Content-Type: application/json'];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);

        if (curl_errno($ch)) {
            $error_msg = 'cURL Error:' . curl_error($ch);
            set_alert('danger', $error_msg);
            log_activity('Xendit Payment Error: ' . $error_msg);
            redirect(site_url('invoice/' . $data['invoice']->id . '/' . $data['invoice']->hash));
        }

        curl_close($ch);
        $response = json_decode($result, true);

        if (isset($response['invoice_url'])) {
            $this->ci->session->set_userdata(['xendit_invoice_hash' => $data['invoice']->hash]);
            redirect($response['invoice_url']);
        } else {
            $error_message = isset($response['message']) ? $response['message'] : 'Unknown error from Xendit.';
            $full_error_log = 'Failed to create Xendit payment invoice: ' . $error_message . ' | Payload Sent: ' . json_encode($payload);
            
            set_alert('danger', 'Gagal membuat invoice pembayaran Xendit: ' . $error_message);
            log_activity($full_error_log);

            redirect(site_url('invoice/' . $data['invoice']->id . '/' . $data['invoice']->hash));
        }
    }
}
