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

class Payment extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->library('midtransservice');
        $this->load->model('Payment_model', 'payment_model');
    }

    /**
     * Proses pembayaran untuk fitur chat
     */
    public function process()
    {
        // Pastikan admin sudah login
        if (!$this->session->userdata('admin_logged_in')) {
            redirect('admin/login');
        }

        $admin_id = $this->session->userdata('admin_id');
        $admin_data = $this->payment_model->get_admin_data($admin_id);

        // Harga fitur chat
        $price = 50000; // Rp 50,000 untuk 30 hari

        // Generate unique order ID
        $order_id = 'CHAT-' . $admin_id . '-' . time() . '-' . rand(1000, 9999);

        // Data transaksi
        $transaction_details = array(
            'order_id' => $order_id,
            'gross_amount' => $price
        );

        // Data pelanggan (admin)
        $customer_details = array(
            'first_name' => $admin_data['nama'],
            'email' => $admin_data['email'],
            'phone' => ''
        );

        // Detail item
        $item_details = array(
            array(
                'id' => 'CHAT-PREMIUM-001',
                'price' => $price,
                'quantity' => 1,
                'name' => 'Fitur Chat Premium (30 Hari)'
            )
        );

        // Generate Snap Token
        $snapToken = $this->midtransservice->createSnapToken(
            $transaction_details,
            $customer_details,
            $item_details
        );

        if ($snapToken) {
            // Simpan data transaksi ke database
            $payment_data = array(
                'id_admin' => $admin_id,
                'order_id' => $order_id,
                'gross_amount' => $price,
                'payment_type' => '',
                'transaction_status' => 'pending',
                'transaction_time' => NULL,
                'raw_response' => json_encode([
                    'snap_token' => $snapToken,
                    'transaction_details' => $transaction_details,
                    'customer_details' => $customer_details,
                    'item_details' => $item_details
                ]),
                'created_at' => date('Y-m-d H:i:s')
            );

            // Simpan ke database
            $this->payment_model->create_payment($payment_data);

            // Kirim data ke view
            $data['snapToken'] = $snapToken;
            $data['client_key'] = $this->config->item('client_key', 'midtrans');
            $data['order_id'] = $order_id;
            $data['amount'] = $price;
            $data['admin_name'] = $admin_data['nama'];

            $this->load->view('admin/payment/snap_payment', $data);
        } else {
            $this->session->set_flashdata('error', 'Gagal memproses pembayaran. Silakan coba lagi.');
            redirect('admin/subscription');
        }
    }
    public function subscription()
    {
        // Pastikan admin sudah login
        if (!$this->session->userdata('admin_logged_in')) {
            redirect('admin/login');
        }

        $admin_id = $this->session->userdata('admin_id');

        // Get admin data
        $admin_data = $this->payment_model->get_admin_data($admin_id);

        if (!$admin_data) {
            // Jika tidak ditemukan via model, coba langsung dari database
            $admin_data = $this->db->get_where('admin', ['id' => $admin_id])->row_array();
        }

        if (!$admin_data) {
            $this->session->set_flashdata('error', 'Data admin tidak ditemukan.');
            redirect('admin/dashboard');
        }

        // Get current subscription
        $current_subscription = $this->payment_model->get_admin_subscription($admin_id);
        $is_chat_active = $this->payment_model->is_chat_active($admin_id);

        $data = [
            'title' => 'Langganan Fitur Chat',
            'admin' => (object) $admin_data, // Convert to object untuk view
            'current_subscription' => $current_subscription,
            'is_chat_active' => $is_chat_active,
            'price' => 50000, // Harga tetap Rp 50,000
            'duration' => 30 // 30 hari
        ];

        // Load admin template
        $this->load->view('admin/templates/header', $data);
        $this->load->view('admin/payment/checkout', $data);
        $this->load->view('admin/templates/footer');
    }

    /**
     * Handle notification/webhook dari Midtrans
     */
    public function notification()
    {
        // Get POST data
        $json_result = file_get_contents('php://input');
        $result = json_decode($json_result);

        log_message('info', 'Midtrans Notification: ' . $json_result);

        if ($result) {
            try {
                $notification = $this->midtransservice->handleNotification();

                if ($notification) {
                    $order_id = $notification->order_id;
                    $transaction_status = $notification->transaction_status;
                    $fraud_status = $notification->fraud_status;

                    // Get payment data
                    $payment = $this->payment_model->get_payment_by_order_id($order_id);

                    if ($payment) {
                        // Update payment status
                        $update_data = [
                            'transaction_status' => $transaction_status,
                            'payment_type' => $notification->payment_type,
                            'transaction_time' => date('Y-m-d H:i:s', strtotime($notification->transaction_time)),
                            'raw_response' => json_encode($notification)
                        ];

                        $this->payment_model->update_payment_status($order_id, $update_data);

                        // Jika pembayaran sukses, aktifkan fitur chat
                        if ($transaction_status == 'settlement' || $transaction_status == 'capture') {
                            if ($fraud_status == 'accept') {
                                // Aktifkan fitur chat untuk 30 hari
                                $this->payment_model->activate_chat_feature($payment['id_admin'], 30);

                                log_message('info', 'Chat feature activated for admin ID: ' . $payment['id_admin']);
                            }
                        }

                        // Response ke Midtrans
                        http_response_code(200);
                        echo json_encode(['status' => 'success', 'message' => 'Notification processed']);
                        return;
                    }
                }
            } catch (Exception $e) {
                log_message('error', 'Midtrans Notification Error: ' . $e->getMessage());
            }
        }

        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid notification']);
    }

    /**
     * Halaman sukses pembayaran
     */
    public function success()
    {
        if (!$this->session->userdata('admin_logged_in')) {
            redirect('admin/login');
        }

        $order_id = $this->input->get('order_id');
        $admin_id = $this->session->userdata('admin_id');

        $data['title'] = 'Pembayaran Berhasil';
        $data['order_id'] = $order_id;
        $data['admin_id'] = $admin_id;

        $this->load->view('admin/payment/success', $data);
    }

    /**
     * Halaman gagal pembayaran
     */
    public function failed()
    {
        if (!$this->session->userdata('admin_logged_in')) {
            redirect('admin/login');
        }

        $data['title'] = 'Pembayaran Gagal';
        $data['error'] = $this->session->flashdata('error') ?: 'Pembayaran tidak berhasil. Silakan coba lagi.';

        $this->load->view('admin/payment/failed', $data);
    }

    /**
     * Handle redirect setelah pembayaran
     */
    public function finish()
    {
        $order_id = $this->input->get('order_id');
        $status_code = $this->input->get('status_code');
        $transaction_status = $this->input->get('transaction_status');

        if ($status_code == '200' && ($transaction_status == 'settlement' || $transaction_status == 'capture')) {
            redirect('payment/success?order_id=' . $order_id);
        } else {
            $this->session->set_flashdata('error', 'Pembayaran gagal. Status: ' . $transaction_status);
            redirect('payment/failed');
        }
    }

    /**
     * Halaman history pembayaran
     */
    public function history()
    {
        if (!$this->session->userdata('admin_logged_in')) {
            redirect('admin/login');
        }

        $admin_id = $this->session->userdata('admin_id');

        // Get payments
        $payments = $this->payment_model->get_payments_by_admin($admin_id, 20, 0);

        // Get subscription info
        $subscription = $this->payment_model->get_admin_subscription($admin_id);
        $is_chat_active = $this->payment_model->is_chat_active($admin_id);
        $total_spent = $this->payment_model->get_total_payments_amount($admin_id);

        $data = [
            'title' => 'History Pembayaran',
            'payments' => $payments,
            'subscription' => $subscription,
            'is_chat_active' => $is_chat_active,
            'total_spent' => $total_spent,
            'active_until' => $subscription ? $subscription['end_date'] : null
        ];

        $this->load->view('admin/payment/history', $data);
    }
}
