<?php

class ChainPay_Usage_Tracker {
    
    private $table_name;
    
    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'chainpay_usage';
    }
    
    public function track($license_id, $feature, $count = 1) {
        global $wpdb;
        
        $period = $this->get_current_period();
        $period_start = $period['start'];
        $period_end = $period['end'];
        
        $existing = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$this->table_name} 
             WHERE license_id = %d AND feature = %s AND period = %s AND period_start = %s",
            $license_id,
            $feature,
            $period['type'],
            $period_start
        ));
        
        if ($existing) {
            $wpdb->update(
                $this->table_name,
                array(
                    'count' => $existing->count + $count,
                    'updated_at' => current_time('mysql')
                ),
                array('id' => $existing->id),
                array('%d', '%s'),
                array('%d')
            );
            return $existing->count + $count;
        } else {
            $wpdb->insert(
                $this->table_name,
                array(
                    'license_id' => $license_id,
                    'feature' => $feature,
                    'count' => $count,
                    'period' => $period['type'],
                    'period_start' => $period_start,
                    'period_end' => $period_end
                ),
                array('%d', '%s', '%d', '%s', '%s', '%s')
            );
            return $count;
        }
    }
    
    public function get_usage($license_id, $feature = '', $period = 'daily') {
        global $wpdb;
        
        $period_data = $this->get_current_period($period);
        
        if ($feature) {
            return $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM {$this->table_name} 
                 WHERE license_id = %d AND feature = %s AND period = %s AND period_start = %s",
                $license_id,
                $feature,
                $period_data['type'],
                $period_data['start']
            ));
        }
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->table_name} 
             WHERE license_id = %d AND period = %s AND period_start = %s",
            $license_id,
            $period_data['type'],
            $period_data['start']
        ));
    }
    
    public function check_limit($license_id, $feature, $limit, $period = 'daily') {
        $usage = $this->get_usage($license_id, $feature, $period);
        
        if (!$usage) {
            return array(
                'allowed' => true,
                'used' => 0,
                'limit' => $limit,
                'remaining' => $limit
            );
        }
        
        $remaining = max(0, $limit - $usage->count);
        
        return array(
            'allowed' => $remaining > 0,
            'used' => $usage->count,
            'limit' => $limit,
            'remaining' => $remaining
        );
    }
    
    public function increment($license_id, $feature, $count = 1) {
        return $this->track($license_id, $feature, $count);
    }
    
    public function decrement($license_id, $feature, $count = 1) {
        global $wpdb;
        
        $period = $this->get_current_period();
        
        $usage = $this->get_usage($license_id, $feature, $period['type']);
        
        if ($usage && $usage->count >= $count) {
            $wpdb->update(
                $this->table_name,
                array(
                    'count' => $usage->count - $count,
                    'updated_at' => current_time('mysql')
                ),
                array('id' => $usage->id),
                array('%d', '%s'),
                array('%d')
            );
            return $usage->count - $count;
        }
        
        return 0;
    }
    
    public function reset($license_id, $feature = '') {
        global $wpdb;
        
        if ($feature) {
            return $wpdb->delete(
                $this->table_name,
                array('license_id' => $license_id, 'feature' => $feature),
                array('%d', '%s')
            );
        }
        
        return $wpdb->delete(
            $this->table_name,
            array('license_id' => $license_id),
            array('%d')
        );
    }
    
    public function get_all_usage($license_id) {
        global $wpdb;
        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->table_name} WHERE license_id = %d ORDER BY period_start DESC",
            $license_id
        ));
    }
    
    public function get_total_usage($license_id, $feature = '') {
        global $wpdb;
        
        if ($feature) {
            return $wpdb->get_var($wpdb->prepare(
                "SELECT SUM(count) FROM {$this->table_name} WHERE license_id = %d AND feature = %s",
                $license_id,
                $feature
            ));
        }
        
        return $wpdb->get_results($wpdb->prepare(
            "SELECT feature, SUM(count) as total FROM {$this->table_name} WHERE license_id = %d GROUP BY feature",
            $license_id
        ));
    }
    
    private function get_current_period($period_type = 'daily') {
        $now = current_time('mysql');
        $period_types = array(
            'hourly' => array(
                'start' => date('Y-m-d H:00:00', strtotime($now)),
                'end' => date('Y-m-d H:59:59', strtotime($now)),
                'type' => 'hourly'
            ),
            'daily' => array(
                'start' => date('Y-m-d 00:00:00', strtotime($now)),
                'end' => date('Y-m-d 23:59:59', strtotime($now)),
                'type' => 'daily'
            ),
            'weekly' => array(
                'start' => date('Y-m-d 00:00:00', strtotime('monday this week', strtotime($now))),
                'end' => date('Y-m-d 23:59:59', strtotime('sunday this week', strtotime($now))),
                'type' => 'weekly'
            ),
            'monthly' => array(
                'start' => date('Y-m-01 00:00:00', strtotime($now)),
                'end' => date('Y-m-t 23:59:59', strtotime($now)),
                'type' => 'monthly'
            ),
            'yearly' => array(
                'start' => date('Y-01-01 00:00:00', strtotime($now)),
                'end' => date('Y-12-31 23:59:59', strtotime($now)),
                'type' => 'yearly'
            )
        );
        
        return $period_types[$period_type] ?? $period_types['daily'];
    }
    
    public function cleanup_old_records($days = 90) {
        global $wpdb;
        
        $cutoff = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        
        return $wpdb->query($wpdb->prepare(
            "DELETE FROM {$this->table_name} WHERE period_start < %s",
            $cutoff
        ));
    }
}
