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

class Webhook extends CI_Controller
{
    private $Midtransservice;
    private $payment_model;
    private $subscription_model;
    
    public function __construct()
    {
        parent::__construct();
        
        // Disable CSRF for webhook
        $this->config->set_item('csrf_protection', false);
        
        // Load models
        $this->load->model('Payment_model', 'payment_model');
        $this->load->model('Subscription_model', 'subscription_model');
        $this->load->library('Midtransservice');
        
        // Set JSON header
        header('Content-Type: application/json');
    }
    
    /**
     * Handle Midtrans webhook notifications
     */
    public function handle()
    {
        // Log incoming webhook
        $raw_input = file_get_contents('php://input');
        log_message('info', 'Midtrans Webhook Received: ' . $raw_input);
        
        // Validate notification
        $validation = $this->Midtransservice->validate_notification();
        
        if (!$validation['success']) {
            log_message('error', 'Webhook Validation Failed: ' . $validation['error']);
            echo json_encode(['status' => 'error', 'message' => 'Invalid notification']);
            return;
        }
        
        $notification = $validation['data'];
        $order_id = $notification->order_id;
        $transaction_status = $notification->transaction_status;
        $fraud_status = $notification->fraud_status ?? null;
        
        log_message('info', "Processing webhook for Order ID: {$order_id}, Status: {$transaction_status}");
        
        // Get payment record
        $payment = $this->payment_model->get_payment_by_order($order_id);
        
        if (!$payment) {
            log_message('error', "Payment not found for Order ID: {$order_id}");
            echo json_encode(['status' => 'error', 'message' => 'Payment not found']);
            return;
        }
        
        // Prepare update data
        $update_data = [
            'transaction_status' => $transaction_status,
            'fraud_status' => $fraud_status,
            'payment_type' => $notification->payment_type ?? null,
            'transaction_time' => $notification->transaction_time ?? date('Y-m-d H:i:s'),
            'raw_response' => json_encode($notification)
        ];
        
        // Update payment record
        $this->payment_model->update_payment($order_id, $update_data);
        
        // Handle different statuses
        switch ($transaction_status) {
            case 'capture':
                if ($fraud_status == 'challenge') {
                    // TODO: Set payment status in merchant's database to 'challenge'
                    $this->handle_challenge($payment);
                } else if ($fraud_status == 'accept') {
                    // Payment successful
                    $this->handle_success($payment);
                }
                break;
                
            case 'settlement':
                // Payment successful
                $this->handle_success($payment);
                break;
                
            case 'pending':
                // Payment pending
                $this->handle_pending($payment);
                break;
                
            case 'deny':
                // Payment denied
                $this->handle_deny($payment);
                break;
                
            case 'cancel':
            case 'expire':
                // Payment cancelled or expired
                $this->handle_cancel_expire($payment);
                break;
        }
        
        // Send real-time notification via WebSocket (if configured)
        $this->send_realtime_notification($payment, $transaction_status);
        
        echo json_encode(['status' => 'ok', 'message' => 'Webhook processed successfully']);
    }
    
    /**
     * Handle successful payment
     */
    private function handle_success($payment)
    {
        $admin_id = $payment->id_admin;
        
        // Activate subscription
        $subscription_data = [
            'order_id' => $payment->order_id,
            'payment_type' => $payment->payment_type,
            'gross_amount' => $payment->gross_amount
        ];
        
        $this->subscription_model->activate_subscription($admin_id, $subscription_data);
        
        log_message('info', "Subscription activated for admin ID: {$admin_id} via Order ID: {$payment->order_id}");
        
        // Send email notification (optional)
        // $this->send_email_notification($payment, 'success');
    }
    
    /**
     * Handle pending payment
     */
    private function handle_pending($payment)
    {
        log_message('info', "Payment pending for Order ID: {$payment->order_id}");
        
        // Send email notification (optional)
        // $this->send_email_notification($payment, 'pending');
    }
    
    /**
     * Handle denied payment
     */
    private function handle_deny($payment)
    {
        log_message('info', "Payment denied for Order ID: {$payment->order_id}");
        
        // Send email notification (optional)
        // $this->send_email_notification($payment, 'deny');
    }
    
    /**
     * Handle cancelled or expired payment
     */
    private function handle_cancel_expire($payment)
    {
        log_message('info', "Payment cancelled/expired for Order ID: {$payment->order_id}");
        
        // Send email notification (optional)
        // $this->send_email_notification($payment, 'cancel');
    }
    
    /**
     * Handle challenge (fraud detection)
     */
    private function handle_challenge($payment)
    {
        log_message('info', "Payment under challenge for Order ID: {$payment->order_id}");
        
        // Send email notification (optional)
        // $this->send_email_notification($payment, 'challenge');
    }
    
    /**
     * Send real-time notification via WebSocket
     */
    private function send_realtime_notification($payment, $status)
    {
        // Prepare notification data
        $notification_data = [
            'type' => 'payment_update',
            'admin_id' => $payment->id_admin,
            'order_id' => $payment->order_id,
            'status' => $status,
            'amount' => $payment->gross_amount,
            'timestamp' => time(),
            'item_name' => $payment->item_name ?? 'Chat Feature Subscription'
        ];
        
        // Send to WebSocket server (implement based on your WebSocket setup)
        // $this->send_to_websocket($notification_data);
        
        // For now, log it
        log_message('info', 'Real-time notification: ' . json_encode($notification_data));
    }
    
    /**
     * Test webhook endpoint
     */
    public function test()
    {
        echo json_encode([
            'status' => 'ok',
            'message' => 'Webhook endpoint is working',
            'timestamp' => date('Y-m-d H:i:s'),
            'server_time' => time()
        ]);
    }
}