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

class Webhook_model extends My_Model {

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

    /* public function getAndroidNotificationType($key){
        $notification_types = [
            '1' => "SUBSCRIPTION_RECOVERED",
            '2' => "SUBSCRIPTION_RENEWED",
            '3' => "SUBSCRIPTION_CANCELED",
            '4' => "SUBSCRIPTION_PURCHASED",
            '5' => "SUBSCRIPTION_ON_HOLD",
            '6' => "SUBSCRIPTION_IN_GRACE_PERIOD",
            '7' => "SUBSCRIPTION_RESTARTED",
            '8' => "SUBSCRIPTION_PRICE_CHANGE_CONFIRMED",
            '9' => "SUBSCRIPTION_DEFERRED",
            '10' => "SUBSCRIPTION_PAUSED",
            '11' => "SUBSCRIPTION_PAUSE_SCHEDULE_CHANGED",
            '12' => "SUBSCRIPTION_REVOKED",
            '13' => "SUBSCRIPTION_EXPIRED",
        ];
        if(array_key_exists($key, $notification_types)){
            return $notification_types[$key];
        }else{
            return '';
        }
    } */

    public function getAndroidNotificationType($paymentResponse){
        if($paymentResponse['paymentState'] == 2){
            return "INITIAL_BUY";
        }elseif($paymentResponse['paymentState'] == 1){
            return "SUBSCRIBED";
        }elseif($paymentResponse['expiryTimeMillis'] <= (time() * 1000)){
            return "EXPIRED";
        }elseif($paymentResponse['userCancellationTimeMillis'] > 0){
            return "CANCEL";
        }else{
            return "SUBSCRIPTION_RECOVERED";
        }
    }

    public function getCancelReasonForAndroidReceipt($key){
        $cancel_reason = [
            "0" => "User canceled the subscription",
            "1" => "Subscription was canceled by the system, for example because of a billing problem",
            "2" => "Subscription was replaced with a new subscription",
            "3" => "Subscription was canceled by the developer",
        ];
        if(array_key_exists($key, $cancel_reason)){
            return $cancel_reason[$key];
        }else{
            return '';
        }
    }

    public function formatAndSaveWebhookData($obj){
        $transaction = [
            'notification_store' => $obj['notification_store'] ?? APP_STORE_APPLE,
            'notification_type' => $obj['notification_type'] ?? '',
            'environment' => $obj['environment'] ?? '',
            'auto_renew_product_id' => $obj['auto_renew_product_id'] ?? '',
            'auto_renew_status' => $obj['auto_renew_status'] ?? '',
            'auto_renew_status_change_date_ms' => $obj['auto_renew_status_change_date_ms'] ?? 0,
            'password' => '',
            'bid' => '',
            'bvrs' => '',
            'latest_receipt' => $obj['latest_receipt'] ?? '',
            'in_app_ownership_type' => 'PURCHASED',
            'purchase_date_ms' => $obj['purchase_date_ms'] ?? 0,
            'original_purchase_date_ms' => $obj['original_purchase_date_ms'] ?? 0,
            'transaction_id' => $obj['transaction_id'],
            'original_transaction_id' => $obj['original_transaction_id'],
            'quantity' => 1,
            'expires_date_ms' => $obj['expires_date_ms'] ?? 0,
            'product_id' =>$obj['product_id'],
            'is_trial_period' => $obj['is_trial_period'],
            'is_in_intro_offer_period' => 0,
            'expiration_intent' => $obj['expiration_intent'] ?? '',
            'cancellation_date_ms' => $obj['cancellation_date_ms'] ?? 0,
            'price' => $obj['price'] ?? 0,
            'created_at' => time(),
        ];
        return $this->storeWebhookData($transaction);
    }

    public function storeWebhookData($webhook_data)
    {
        $is_premium_subscription = (in_array($webhook_data['product_id'],PREMIUM_SUBSCRIPTION_PACKAGES)) ? TRUE : FALSE;
        $subscription = [
            'notification_store' => $webhook_data['notification_store'],
            'notification_type' => $webhook_data['notification_type'],
            'environment' => $webhook_data['environment'],
            'auto_renew_product_id' => $webhook_data['auto_renew_product_id'],
            'auto_renew_status' => $webhook_data['auto_renew_status'],
            'auto_renew_status_change_date_ms' => $webhook_data['auto_renew_status_change_date_ms'],
            'password' => $webhook_data['password'],
            'bid' => $webhook_data['bid'],
            'bvrs' => $webhook_data['bvrs'],
            // 'latest_receipt' => $webhook_data['latest_receipt'],
            'in_app_ownership_type' => $webhook_data['in_app_ownership_type'],
            'purchase_date_ms' => $webhook_data['purchase_date_ms'],
            'original_purchase_date_ms' => $webhook_data['original_purchase_date_ms'],
            'transaction_id' => $webhook_data['transaction_id'],
            'original_transaction_id' => $webhook_data['original_transaction_id'],
            'quantity' => $webhook_data['quantity'],
            'expires_date_ms' => $webhook_data['expires_date_ms'],
            'product_id' => $webhook_data['product_id'],
            'is_premium_subscription' => $is_premium_subscription,
            'is_trial_period' => $webhook_data['is_trial_period'],
            'is_in_intro_offer_period' => $webhook_data['is_in_intro_offer_period'],
            'expiration_intent' => $webhook_data['expiration_intent'],
            'cancellation_date_ms' => $webhook_data['cancellation_date_ms'],
            'price' => $webhook_data['price'] ?? 0,
            'created_at' => time(),
            'is_latest_webhook' => TRUE,
        ];
        $receipt = [
            'transaction_id' => $webhook_data['transaction_id'],
            'latest_receipt' => $webhook_data['latest_receipt'],
        ];
        $flag = $this->db->insert($this->webhook_subscription_table,$subscription);
        if(!$flag){ return FALSE; }
        $flag = $this->updateLatestFlag($webhook_data['original_transaction_id'], $this->db->insert_id());
        if(!$flag){ return FALSE; }

        $checkReceiptIsExistParams = ['transaction_id' => $webhook_data['transaction_id']];
        $checkReceiptIsExist = $this->db->from($this->subscription_receipt_table)->where($checkReceiptIsExistParams)->get()->num_rows();
        
        if($checkReceiptIsExist > 0){
            $this->db->where($checkReceiptIsExistParams);
            $flag = $this->db->update($this->subscription_receipt_table,['latest_receipt' => $webhook_data['latest_receipt']]);
            if(!$flag){ return FALSE; }
        }else{
            $flag = $this->db->insert($this->subscription_receipt_table,$receipt);
            if(!$flag){ return FALSE; }
        }
        return TRUE;
    }

    function updateLatestFlag($original_transaction_id, $last_id){
        $this->db->where('original_transaction_id',$original_transaction_id);
        $this->db->where('webhook_subscription_id != ',$last_id);
        $flag = $this->db->update($this->webhook_subscription_table,['is_latest_webhook'=>FALSE]);
        return $flag;
    }

    function fetch_wholesaler_users($params){
        $params = init_model_params($params);
        $fields = ["device.wholesaler_user","device.user_device_id"];
        $this->db->select($fields);
        $this->db->from($this->user_subscription_table.' AS usubscription');
        $this->db->join($this->user_device_table.' AS device','device.user_device_id = usubscription.user_device_id');
        get_where($params['where']);
        $this->db->distinct();
        $query = $this->db->get();
        return get_data($params, $query);
    }
}