<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
class Payment_Model_DbTable_Subscriptions extends Engine_Db_Table
{
  protected $_rowClass = 'Payment_Model_Subscription';

  public function check(User_Model_User $user)
  {
    $packagesTable = Engine_Api::_()->getDbtable('packages', 'payment');
    $gatewaysTable = Engine_Api::_()->getDbtable('gateways', 'payment');

    // Have any gateways or packages been added yet?
    if( $gatewaysTable->getEnabledGatewayCount() <= 0 ||
        $packagesTable->getEnabledNonFreePackageCount() <= 0 ) {
      return true;
    }

    // Check for the user's plan
    $subscription = $this->fetchRow(array(
      'user_id = ?' => $user->getIdentity(),
      'active = ?' => true,
    ));

    // Check if there is no subscription
    if( !$subscription ) {

      // Check if they are an admin or moderator (don't require subscriptions from them)
      $level = Engine_Api::_()->getItem('authorization_level', $user->level_id);
      if( engine_in_array($level->type, array('admin', 'moderator')) ) {
        return true;
      }

      return null;
    }

    // Subscription is active
    if( $subscription->status == 'active' || $subscription->status == 'trial' ) {
      return true;
    }

    // Get the package
    $package = $packagesTable->find($subscription->package_id)
      ->current();

    // If there is no plan, return null
    if( !$package ) {
      return null;
    }

    // If this is a free plan, return true
//    if( $package->price <= 0 ) {
//      return true;
//    }

    // Subscription needs to be paid
    return false;
  }

  public function cancelAll(User_Model_User $user, $note = null,
      Payment_Model_Subscription $except = null)
  {
    $select = $this->select()
      ->where('user_id = ?', $user->getIdentity())
      ->where('active = ?', true)
      ;

    if( $except ) {
      $select->where('subscription_id != ?', $except->subscription_id);
    }
    foreach( $this->fetchAll($select) as $subscription ) {
      try {
        $subscription->cancel();
        if($except) {
            $package = $subscription->getPackage();
            $currentPackage = $except->getPackage();
            $viewer = Engine_Api::_()->user()->getViewer();
            Engine_Api::_()->getDbtable('notifications', 'activity')->addNotification($subscription->getUser(), $viewer, $subscription->getUser(), 'payment_subscription_changed',array('currentPlan'=> $package->title,'changedPlan'=> $currentPackage->title));
            Engine_Api::_()->getApi('mail', 'core')->sendSystem($subscription->getUser(), 'payment_subscription_changed', array(
              'subscription_title' => $currentPackage->title,
              'current_plan'=> $package->title,
              'changed_plan'=> $currentPackage->title,
              'subscription_description' => $currentPackage->description,
              'subscription_terms' => $currentPackage->getPackageDescription(),
              'object_link' => 'http://' . $_SERVER['HTTP_HOST'] .
              Zend_Controller_Front::getInstance()->getRouter()->assemble(array(), 'user_login', true),
            ));
        }
      } catch( Exception $e ) {
        $subscription->getGateway()->getPlugin()->getLog()
          ->log($e->__toString(), Zend_Log::ERR);
      }
    }

    return $this;
  }

  public function activateDefaultPlan(User_Model_User $user)
  {
    $packagesTable = Engine_Api::_()->getDbtable('packages', 'payment');
    $gatewaysTable = Engine_Api::_()->getDbtable('gateways', 'payment');

    // Have any gateways or packages been added yet?
    if( $gatewaysTable->getEnabledGatewayCount() <= 0 ||
        $packagesTable->getEnabledNonFreePackageCount() <= 0 ) {
      return false;
    }

    // See if they've had a plan before
    $hasSubscription = (bool) $this->select()
        ->from($this, new Zend_Db_Expr('TRUE'))
        ->where('user_id = ?', $user->getIdentity())
        ->limit(1)
        ->query()
        ->fetchColumn();
    if( $hasSubscription ) {
      return false;
    }

    // Get the default package
    $package = $packagesTable->fetchRow(array(
      '`default` = ?' => true,
      'enabled = ?' => true,
      'price <= ?' => 0,
    ));

    if( !$package ) {
      return false;
    }

    // Create the default subscription
    $subscription = $this->createRow();
    $subscription->setFromArray(array(
      'package_id' => $package->package_id,
      'user_id' => $user->getIdentity(),
      'status' => 'initial',
      'active' => false,
      'creation_date' => new Zend_Db_Expr('NOW()'),
    ));
    $subscription->save();

    // Set active
    $subscription->setActive(true);
    $subscription->onPaymentSuccess();

    return $subscription;
  }

  public function isSignupSubscriptionEnable()
  {
    $table = Engine_Api::_()->getDbtable('signup', 'user');
    $step_row = $table->fetchRow($table->select()->where('class = ?', 'Payment_Plugin_Signup_Subscription'));
    return $step_row->enable;
  }
  
  public function userCurrentSubscriptionPlan($params = array()) {
    $tableName = $this->info('name');
    $select = $this->select()
                    ->where('user_id = ?', $params['user_id'])
                    ->where('resource_type = ?', $params['resource_type'])
                    ->where('resource_id = ?', $params['resource_id'])
                    ->where('status = ?', 'active');
    return $this->fetchRow($select);
  }

  public function currentSubscriptionFirstPlan($user) {

    $select = $this->select()
            ->where('user_id = ?', $user->getIdentity())
            //->where('active = ?', false)
            //->where('status = ?', 'initial')
            ->order('subscription_id DESC')
            ->limit(1);
    return $this->fetchRow($select);
  }

	public function memberCurrentSubscription() {
		$viewer = Engine_Api::_()->user()->getViewer();
		$currentSubscription = $this->fetchRow(array(
			'user_id = ?' => $viewer->getIdentity(),
			'active = ?' => true,
		));
		return $currentSubscription;
	}
}
