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

class Subscription_model extends My_Model {

    public function __construct()
    {
        parent::__construct();
    }

    public function getDatatableList($params = [])
    {
        $params = init_model_params($params);
        $fields = array_merge(API_FIELDS_WEBHOOK_SUBSCRIPTION, API_FIELDS_DEVICE, ['web_subscription.created_at']);
        $this->db->select($fields);
        get_where($params['where']);
        get_filter_where(DEVICE_USERS_SEARCHABLE_FIELDS);
        $this->db->from($this->webhook_subscription_table.' AS web_subscription');
        $this->db->join($this->user_subscription_table.' AS usubscription','web_subscription.original_transaction_id = usubscription.original_transaction_id AND usubscription.is_latest_webhook_subscription = 1','LEFT');
        $this->db->join($this->user_device_table.' AS device','device.user_device_id = usubscription.user_device_id','LEFT');
        if($params['action'] != 'count'){
            get_filter_order($_REQUEST, $params['order'], DEVICE_USERS_ORDERABLE_FIELDS);
            get_limit($params['limit'], $params['offset']);
        }
        get_limit($params['limit'],$params['offset']);
        $this->db->group_by('usubscription.original_transaction_id');
        $query = $this->db->get();
        return get_data($params, $query);
    }

    private function getAppleNotificationStoreCondition(){
        return ['web_subscription.notification_store' => APP_STORE_APPLE];
    }

    private function getAndroidNotificationStoreCondition(){
        return ['web_subscription.notification_store' => APP_STORE_ANDROID];
    }
    
    private function getPaidSubscriberCountConditions(){
        return [
            'web_subscription.is_premium_subscription' => 1, 'web_subscription.is_expired' => 0, 'web_subscription.is_trial_period' => 0, 
            'web_subscription.is_latest_webhook' => 1
        ];
    }
    
    private function getTrialSubscriberCountConditions(){
        return [
            'web_subscription.is_premium_subscription' => 1, 'web_subscription.is_expired' => 0, 'web_subscription.is_trial_period' => 1, 
            'web_subscription.is_latest_webhook' => 1
        ];
    }
    
    private function getExpiredSubscriberCountConditions(){
        return [
            'web_subscription.is_premium_subscription' => 1, 'web_subscription.is_expired' => 1, 'web_subscription.is_latest_webhook' => 1
        ];
    }

    private function getExpiredSubscribersCountForRangeCondition($range){
        $start = $end = 0;
        switch ($range) {
            case 'today':
                $start = strtotime("today");
                $end = strtotime("tomorrow");
                break;
            case 'yesterday':
                $start = strtotime("yesterday");
                $end = strtotime("today");
                break;
            case 'this-month':
                $start = strtotime(date('Y-m-01'));
                $end = strtotime(date('Y-m-01', strtotime("+1 months", $start)));
                break;
            case 'last-month':
                $start = strtotime(date('Y-m-01', strtotime("-1 month")));
                $end = strtotime(date('Y-m-01', strtotime("+1 months", $start)));
                break;
            
            default:
                # code...
                break;
        }

        if($start > 0 && $end > 0){
            $end--;
            $month_date_range = 'web_subscription.created_at BETWEEN ' . $start . ' AND ' . $end;
            return ['SINGLE_WHERE' => $month_date_range];
        }
    }

    private function getLatestSubscriptionStats($params = []){
        $params['store'] = $params['store'] ?? '';
        $store_condition = [];
        if(!empty($params['store'])){
            if($params['store'] == APP_STORE_APPLE){
                $store_condition = $this->getAppleNotificationStoreCondition();
            }else if($params['store'] == APP_STORE_ANDROID){
                $store_condition = $this->getAndroidNotificationStoreCondition();
            }
        }
        $where = array_merge(
            $store_condition,
            $this->getPaidSubscriberCountConditions()
        );
        $params = ['action' => 'count', 'where' => $where];
        $paid_subscribers = $this->subscription_model->getDatatableList($params);

        $where = array_merge(
            $store_condition,
            $this->getTrialSubscriberCountConditions()
        );
        $params = ['action' => 'count', 'where' => $where];
        $trial_subscribers = $this->subscription_model->getDatatableList($params);
        
        $where = array_merge(
            $store_condition,
            $this->getExpiredSubscriberCountConditions(),
            $this->getExpiredSubscribersCountForRangeCondition("this-month")
        );
        $params = ['action' => 'count', 'where' => $where];
        $expired_subscribers = $this->subscription_model->getDatatableList($params);
    
        $result = [
            'paid_subscribers' => $paid_subscribers,
            'trial_subscribers' => $trial_subscribers,
            'expired_subscribers' => $expired_subscribers
        ];
        return $result;
    }

    public function getLatestSubscriptionStatsStoreWise(){
        $android = $this->getLatestSubscriptionStats(['store' => APP_STORE_ANDROID]);
        $apple = $this->getLatestSubscriptionStats(['store' => APP_STORE_APPLE]);
        return [APP_STORE_ANDROID => $android, APP_STORE_APPLE => $apple];
    }

    public function getMySubscriptionStats($params = []){
        $params = init_model_params($params);
        // $fields = array_merge(API_FIELDS_WEBHOOK_SUBSCRIPTION, API_FIELDS_DEVICE, ['web_subscription.created_at']);
        $this->db->select('subscription_stat.*');
        get_where($params['where']);
        // get_filter_where(DEVICE_USERS_SEARCHABLE_FIELDS);
        $this->db->from($this->subscription_stat_table.' AS subscription_stat');
        if($params['action'] != 'count'){
            // get_filter_order($_REQUEST, $params['order'], DEVICE_USERS_ORDERABLE_FIELDS);
            get_limit($params['limit'], $params['offset']);
        }
        get_limit($params['limit'],$params['offset']);
        $query = $this->db->get();
        return get_data($params, $query);
    }

    public function insertSubscriptionStatsData($postdata){
        $analytics = [];
        $analytics['store'] = $postdata['store'];
        $analytics['stat_date'] = $postdata['stat_date'];
        $analytics['paid_subscribers'] = $postdata['paid_subscribers'];
        $analytics['trial_subscribers'] = $postdata['trial_subscribers'];
        $analytics['expired_subscribers'] = $postdata['expired_subscribers'];
        $this->db->insert($this->subscription_stat_table, $analytics);
        return $this->db->insert_id();
    }

    public function updateSubscriptionStatsData($postdata, $where){
        $analytics = [];
        $analytics['paid_subscribers'] = $postdata['paid_subscribers'];
        $analytics['trial_subscribers'] = $postdata['trial_subscribers'];
        $analytics['expired_subscribers'] = $postdata['expired_subscribers'];
        $this->db->where($where);
        $flag = $this->db->update($this->subscription_stat_table, $analytics);
        if(!$flag){
            return FALSE;
        }
        return TRUE;
    }
}
