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

class Subscription_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    // ==================== PLANS ====================
    
    public function get_all_plans()
    {
        $this->db->where('is_active', 1);
        $this->db->order_by('display_order', 'ASC');
        return $this->db->get('subscription_plans')->result();
    }

    public function get_plan_by_id($id_plan)
    {
        return $this->db->get_where('subscription_plans', ['id_plan' => $id_plan])->row();
    }

    // ==================== SUBSCRIPTIONS ====================
    
    public function get_active_subscription($id_admin)
    {
        $this->db->where('id_admin', $id_admin);
        $this->db->where('status', 'active');
        $this->db->where('start_date <=', date('Y-m-d H:i:s'));
        $this->db->where('end_date >=', date('Y-m-d H:i:s'));
        $this->db->order_by('end_date', 'DESC');
        $this->db->limit(1);
        
        // 🐛 DEBUG: Log the query
        $query = $this->db->get('admin_subscription');
        log_message('debug', '=== GET ACTIVE SUBSCRIPTION ===');
        log_message('debug', 'Admin ID: ' . $id_admin);
        log_message('debug', 'Query: ' . $this->db->last_query());
        log_message('debug', 'Result count: ' . $query->num_rows());
        
        return $query->row();
    }

    public function check_subscription($id_admin)
    {
        $subscription = $this->get_active_subscription($id_admin);
        
        // 🐛 DEBUG: Log check result
        log_message('debug', '=== CHECK SUBSCRIPTION ===');
        log_message('debug', 'Admin ID: ' . $id_admin);
        log_message('debug', 'Has subscription: ' . ($subscription !== null ? 'YES' : 'NO'));
        if ($subscription) {
            log_message('debug', 'Subscription ID: ' . $subscription->id_subscription);
            log_message('debug', 'Status: ' . $subscription->status);
            log_message('debug', 'End date: ' . $subscription->end_date);
        }
        
        return $subscription !== null;
    }

    public function create_subscription($data)
    {
        return $this->db->insert('admin_subscription', $data);
    }

    public function update_subscription($id_subscription, $data)
    {
        $this->db->where('id_subscription', $id_subscription);
        return $this->db->update('admin_subscription', $data);
    }

    public function activate_subscription($id_subscription)
    {
        $this->db->where('id_subscription', $id_subscription);
        $result = $this->db->update('admin_subscription', [
            'status' => 'active',
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        
        // 🐛 DEBUG: Log activation
        log_message('debug', '=== ACTIVATE SUBSCRIPTION ===');
        log_message('debug', 'Subscription ID: ' . $id_subscription);
        log_message('debug', 'Success: ' . ($result ? 'YES' : 'NO'));
        
        return $result;
    }

    public function get_subscription_history($id_admin, $limit = 10)
    {
        $this->db->select('s.*, p.plan_name, p.price');
        $this->db->from('admin_subscription s');
        $this->db->join('subscription_plans p', 'p.id_plan = s.id_plan');
        $this->db->where('s.id_admin', $id_admin);
        $this->db->order_by('s.created_at', 'DESC');
        $this->db->limit($limit);
        return $this->db->get()->result();
    }

    public function expire_subscriptions()
    {
        $this->db->where('status', 'active');
        $this->db->where('end_date <', date('Y-m-d H:i:s'));
        return $this->db->update('admin_subscription', [
            'status' => 'expired',
            'updated_at' => date('Y-m-d H:i:s')
        ]);
    }

    // ==================== PAYMENTS ====================
    
    public function create_payment($data)
    {
        $this->db->insert('payment_transactions', $data);
        return $this->db->insert_id();
    }

    public function update_payment($order_id, $data)
    {
        $this->db->where('order_id', $order_id);
        return $this->db->update('payment_transactions', $data);
    }

    public function get_payment_by_order_id($order_id)
    {
        return $this->db->get_where('payment_transactions', ['order_id' => $order_id])->row();
    }

    public function get_payment_history($id_admin, $limit = 20)
    {
        $this->db->select('t.*, p.plan_name');
        $this->db->from('payment_transactions t');
        $this->db->join('subscription_plans p', 'p.id_plan = t.id_plan');
        $this->db->where('t.id_admin', $id_admin);
        $this->db->order_by('t.created_at', 'DESC');
        $this->db->limit($limit);
        return $this->db->get()->result();
    }

    public function count_pending_payments($id_admin)
    {
        $this->db->where('id_admin', $id_admin);
        $this->db->where('transaction_status', 'pending');
        return $this->db->count_all_results('payment_transactions');
    }

    // ==================== STATISTICS ====================
    
    public function get_subscription_stats($id_admin)
    {
        // Active subscription
        $active = $this->get_active_subscription($id_admin);
        
        // Total spent
        $this->db->select_sum('gross_amount');
        $this->db->where('id_admin', $id_admin);
        $this->db->where('transaction_status', 'settlement');
        $total_spent = $this->db->get('payment_transactions')->row();
        
        // Pending payments
        $pending = $this->count_pending_payments($id_admin);
        
        return [
            'has_active' => $active !== null,
            'active_subscription' => $active,
            'total_spent' => $total_spent ? $total_spent->gross_amount : 0,
            'pending_payments' => $pending
        ];
    }

    // ==================== HELPER ====================
    
    public function generate_order_id($id_admin)
    {
        return 'SUB-' . $id_admin . '-' . time() . '-' . rand(1000, 9999);
    }
    
    // ==================== DEBUG HELPER ====================
    
    /**
     * Get all subscriptions for debugging
     */
    public function debug_get_all_subscriptions($id_admin)
    {
        $this->db->where('id_admin', $id_admin);
        $this->db->order_by('created_at', 'DESC');
        return $this->db->get('admin_subscription')->result();
    }
}