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

require_once APPPATH . '../vendor/autoload.php';

use Midtrans\Config;
use Midtrans\Snap;
use Midtrans\Notification;

class Subscription extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        
        // 🔥 Skip auth check for webhook
        $allowed_public = ['notification'];
        $current_method = $this->router->fetch_method();
        
        if (!in_array($current_method, $allowed_public)) {
            if (!$this->session->userdata('admin_logged_in')) {
                redirect('admin/login');
            }
        }
        
        $this->load->model('admin/Subscription_model');
        $this->load->helper('url');
        $this->load->config('midtrans');
        
        // 🔥 Load custom error suppressor
        $this->load->library('midtrans_override');
        
        Config::$serverKey = $this->config->item('midtrans_server_key');
        Config::$isProduction = $this->config->item('midtrans_is_production');
        Config::$isSanitized = $this->config->item('midtrans_is_sanitized');
        Config::$is3ds = $this->config->item('midtrans_is_3ds');
        
        // 🔥 FIX SSL ERROR + Use improved cURL options
        Config::$curlOptions = $this->midtrans_override->get_curl_options();
    }

    public function process($id_plan)
    {
        try {
            // 1. VALIDATE
            log_message('error', '=== STEP 1: VALIDATE ===');
            if (!$id_plan || !is_numeric($id_plan)) {
                throw new Exception('Invalid plan ID');
            }
            
            $id_admin = $this->session->userdata('admin_id');
            $admin_name = $this->session->userdata('admin_name') ?: 'Admin';
            $admin_email = $this->session->userdata('admin_email') ?: 'admin@sistemkos.com';
            
            log_message('error', 'Admin ID: ' . $id_admin);
            log_message('error', 'Plan ID: ' . $id_plan);
            
            // 2. GET PLAN
            log_message('error', '=== STEP 2: GET PLAN ===');
            $plan = $this->Subscription_model->get_plan_by_id($id_plan);
            
            if (!$plan) {
                throw new Exception('Plan not found');
            }
            
            log_message('error', 'Plan: ' . $plan->plan_name);
            log_message('error', 'Price: ' . $plan->price);
            
            // 3. CREATE ORDER
            log_message('error', '=== STEP 3: CREATE ORDER ===');
            $order_id = $this->Subscription_model->generate_order_id($id_admin);
            log_message('error', 'Order ID: ' . $order_id);
            
            $start_date = date('Y-m-d H:i:s');
            $end_date = date('Y-m-d H:i:s', strtotime("+{$plan->duration_days} days"));
            
            $subscription_data = [
                'id_admin' => $id_admin,
                'id_plan' => $id_plan,
                'start_date' => $start_date,
                'end_date' => $end_date,
                'status' => 'pending',
                'created_at' => date('Y-m-d H:i:s')
            ];
            
            $this->Subscription_model->create_subscription($subscription_data);
            $id_subscription = $this->db->insert_id();
            log_message('error', 'Subscription ID: ' . $id_subscription);
            
            // 4. PREPARE MIDTRANS
            log_message('error', '=== STEP 4: PREPARE MIDTRANS ===');
            
            $transaction = [
                'transaction_details' => [
                    'order_id' => $order_id,
                    'gross_amount' => (int) $plan->price
                ],
                'item_details' => [[
                    'id' => $plan->id_plan,
                    'price' => (int) $plan->price,
                    'quantity' => 1,
                    'name' => $plan->plan_name
                ]],
                'customer_details' => [
                    'first_name' => $admin_name,
                    'email' => $admin_email
                ]
            ];
            
            log_message('error', 'Transaction: ' . json_encode($transaction));
            
            // 5. GET SNAP TOKEN
            log_message('error', '=== STEP 5: GET SNAP TOKEN ===');
            log_message('error', 'Server Key: ' . substr(Config::$serverKey, 0, 15) . '...');
            log_message('error', 'Is Production: ' . (Config::$isProduction ? 'YES' : 'NO'));
            
            // 🔥 Suppress warning dengan @ operator sebagai backup
            $snapToken = @Snap::getSnapToken($transaction);
            
            log_message('error', '✅ SUCCESS! Token: ' . substr($snapToken, 0, 20) . '...');
            
            // 6. SAVE PAYMENT
            log_message('error', '=== STEP 6: SAVE PAYMENT ===');
            $payment_data = [
                'id_admin' => $id_admin,
                'id_subscription' => $id_subscription,
                'id_plan' => $id_plan,
                'order_id' => $order_id,
                'gross_amount' => $plan->price,
                'transaction_status' => 'pending',
                'snap_token' => $snapToken,
                'created_at' => date('Y-m-d H:i:s')
            ];
            
            $this->Subscription_model->create_payment($payment_data);
            log_message('error', 'Payment record saved');
            
            // 7. LOAD VIEW
            log_message('error', '=== STEP 7: LOAD VIEW ===');
            $data['snap_token'] = $snapToken;
            $data['plan'] = $plan;
            $data['order_id'] = $order_id;
            $data['title'] = 'Complete Payment';
            $data['client_key'] = $this->config->item('midtrans_client_key');
            $data['is_production'] = $this->config->item('midtrans_is_production');
            
            log_message('error', 'Loading payment view...');
            $this->load->view('admin/subscription/payment', $data);
            
        } catch (Exception $e) {
            log_message('error', '❌ EXCEPTION: ' . $e->getMessage());
            log_message('error', 'Trace: ' . $e->getTraceAsString());
            
            $this->session->set_flashdata('error', 'ERROR: ' . $e->getMessage());
            redirect('admin/subscription/pricing');
        }
    }

    public function index()
    {
        $id_admin = $this->session->userdata('admin_id');
        
        $data['title'] = 'Subscription Management';
        $data['active_subscription'] = $this->Subscription_model->get_active_subscription($id_admin);
        $data['subscription_stats'] = $this->Subscription_model->get_subscription_stats($id_admin);
        $data['payment_history'] = $this->Subscription_model->get_payment_history($id_admin, 10);
        
        $this->load->view('admin/subscription/index', $data);
    }

    public function pricing()
    {
        $id_admin = $this->session->userdata('admin_id');
        
        $data['title'] = 'Choose Your Plan';
        $data['plans'] = $this->Subscription_model->get_all_plans();
        $data['active_subscription'] = $this->Subscription_model->get_active_subscription($id_admin);
        
        if (empty($data['plans'])) {
            $this->session->set_flashdata('error', 'Tidak ada paket subscription tersedia.');
            redirect('admin/subscription');
        }
        
        $this->load->view('admin/subscription/pricing', $data);
    }

    /**
     * 🔥 Webhook from Midtrans - NO AUTH CHECK!
     */
    public function notification()
    {
        // Disable CI redirect
        header('HTTP/1.1 200 OK');
        header('Content-Type: application/json');
        
        try {
            $json_result = file_get_contents('php://input');
            log_message('error', '=== WEBHOOK RECEIVED ===');
            log_message('error', 'Raw JSON: ' . $json_result);
            
            $notification = new Notification();
            
            $transaction_status = $notification->transaction_status;
            $fraud_status = $notification->fraud_status ?? '';
            $order_id = $notification->order_id;
            $transaction_id = $notification->transaction_id ?? '';
            $payment_type = $notification->payment_type ?? '';
            
            log_message('error', 'Order ID: ' . $order_id);
            log_message('error', 'Status: ' . $transaction_status);
            log_message('error', 'Fraud: ' . $fraud_status);
            log_message('error', 'Payment Type: ' . $payment_type);
            
            $payment = $this->Subscription_model->get_payment_by_order_id($order_id);
            
            if (!$payment) {
                log_message('error', 'Payment not found!');
                echo json_encode(['status' => 'error', 'message' => 'Payment not found']);
                exit;
            }
            
            log_message('error', 'Payment found: ' . $payment->id_transaction);
            
            $update_data = [
                'transaction_id' => $transaction_id,
                'payment_type' => $payment_type,
                'transaction_status' => $transaction_status,
                'transaction_time' => $notification->transaction_time ?? date('Y-m-d H:i:s'),
                'midtrans_response' => $json_result,
                'updated_at' => date('Y-m-d H:i:s')
            ];
            
            // Handle status
            if ($transaction_status == 'capture') {
                if ($fraud_status == 'accept') {
                    $update_data['transaction_status'] = 'success';
                    $update_data['settlement_time'] = date('Y-m-d H:i:s');
                    $this->activate_subscription_for_payment($payment);
                }
            } else if ($transaction_status == 'settlement') {
                $update_data['settlement_time'] = date('Y-m-d H:i:s');
                $this->activate_subscription_for_payment($payment);
            }
            
            $this->Subscription_model->update_payment($order_id, $update_data);
            log_message('error', '✅ Payment updated successfully');
            
            echo json_encode(['status' => 'success']);
            exit;
            
        } catch (Exception $e) {
            log_message('error', '❌ Webhook Error: ' . $e->getMessage());
            log_message('error', 'Trace: ' . $e->getTraceAsString());
            echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
            exit;
        }
    }
    
    private function activate_subscription_for_payment($payment)
    {
        if ($payment->id_subscription) {
            $result = $this->Subscription_model->activate_subscription($payment->id_subscription);
            log_message('error', $result ? '✅ Subscription activated' : '❌ Activation failed');
        }
    }

    public function finish()
    {
        $order_id = $this->input->get('order_id');
        
        if ($order_id) {
            $payment = $this->Subscription_model->get_payment_by_order_id($order_id);
            
            if ($payment) {
                if (in_array($payment->transaction_status, ['settlement', 'success', 'capture'])) {
                    $this->session->set_flashdata('success', '✅ Pembayaran berhasil!');
                } else if ($payment->transaction_status == 'pending') {
                    $this->session->set_flashdata('warning', '⏳ Pembayaran masih diproses.');
                } else {
                    $this->session->set_flashdata('error', '❌ Pembayaran gagal.');
                }
            }
        }
        
        redirect('admin/subscription');
    }

    public function error()
    {
        $this->session->set_flashdata('error', '❌ Pembayaran gagal.');
        redirect('admin/subscription/pricing');
    }

    public function pending()
    {
        $this->session->set_flashdata('warning', '⏳ Pembayaran belum selesai.');
        redirect('admin/subscription');
    }
}