<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
class Storage_Api_Core extends Core_Api_Abstract
{
  const SPACE_LIMIT_REACHED_CODE = 3999;
  
  public function getService($serviceIdentity = null)
  {
    return Engine_Api::_()->getDbtable('services', 'storage')
      ->getService($serviceIdentity);
  }

  public function get($id, $relationship = null)
  {
    return Engine_Api::_()->getItemTable('storage_file')
        ->getFile($id, $relationship);
  }

  public function lookup($id, $relationship)
  {
    return Engine_Api::_()->getItemTable('storage_file')
        ->lookupFile($id, $relationship);
  }

  public function create($file, $params)
  {
    return Engine_Api::_()->getItemTable('storage_file')
        ->createFile($file, $params);
  }

  public function getStorageLimits()
  {
    return Engine_Api::_()->getItemTable('storage_file')
        ->getStorageLimits();
  }
  
  //$file_id is file id or storage path of image
  public function deleteExternalsFiles($file_id) {
  
		if(is_string($file_id)) {
			$file_id = Engine_Api::_()->getDbTable('files', 'storage')->getFileId($file_id);
		}
		
		$file = Engine_Api::_()->getItem('storage_file', $file_id);
		if($file) {
			$service_id = $file->service_id;
			if($service_id == 1) {
				//Delete image
				@unlink($file->storage_path);
				
				$dirPath = APPLICATION_PATH . DIRECTORY_SEPARATOR . str_replace(basename($file->storage_path),"",$file->storage_path);
				if(@is_dir($dirPath)){
					@rmdir($dirPath);
				}
				
			} else if($service_id != 1) {
				$service = Engine_Api::_()->getDbTable('services', 'storage')->getService($service_id);
        $service->removeFile($file->storage_path);
			}
		}
  }

	/**
   * Check user upload quota
   *
   * @param User_Model_User $viewer
   * @param array|string $files $_FILES array OR single file path
   * @return array
   */
  public function checkUploadQuota($viewer, $files)
  {
    $response = array(
      'status' => 1,
      'error' => null,
      'space_limit' => 0,
      'space_used' => 0,
      'space_required' => 0,
    );

    // Get quota limit
    $space_limit = (int) Engine_Api::_()->authorization()->getPermission($viewer->level_id, 'user', 'quota');

    $response['space_limit'] = $space_limit;

    // Unlimited quota
    if ($space_limit <= 0) {
      return $response;
    }

    // Get used storage
    $storageTable = Engine_Api::_()->getDbTable('files', 'storage');
    $tableName = $storageTable->info('name');

    $space_used = (int) $storageTable->select()
      ->from($tableName, new Zend_Db_Expr('SUM(size)'))
      ->where('user_id = ?', (int) $viewer->getIdentity())
      ->query()
      ->fetchColumn();
    $response['space_used'] = $space_used;
    // Calculate upload size
    $space_required = 0;
    // Multiple upload support
    if (is_array($files)) {
      // Case: $_FILES['Filedata']
      if (isset($files['tmp_name'])) {
        // Multiple files
        if (is_array($files['tmp_name'])) {
          foreach ($files['tmp_name'] as $tmpFile) {
            if (!empty($tmpFile) && file_exists($tmpFile)) {
              $space_required += filesize($tmpFile);
            }
          }
        } else {
          // Single file
          if (!empty($files['tmp_name']) && file_exists($files['tmp_name'])) {
            $space_required += filesize($files['tmp_name']);
          }
        }
      } else {
        // Direct multiple file paths array
        foreach ($files as $file) {
          if (!empty($file) && file_exists($file)) {
            $space_required += filesize($file);
          }
        }
      }
    } else {
      // Single file path
      if (!empty($files) && file_exists($files)) {
        $space_required += filesize($files);
      }
    }
		
    // Final quota check
    if (($space_used + $space_required) > $space_limit) {
      $response['status'] = false;
      $response['error'] = array(array('errorMessage' => Zend_Registry::get('Zend_Translate')->_('File creation failed. You may be over your upload limit. Try uploading a smaller file, or delete some files to free up space.')));
    }
    return $response;
  }
}
