1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 371: 372: 373: 374: 375: 376: 377: 378: 379: 380: 381: 382: 383: 384: 385: 386: 387: 388: 389: 390: 391: 392: 393: 394: 395: 396: 397: 398: 399: 400: 401: 402: 403: 404: 405: 406: 407: 408: 409: 410: 411: 412: 413: 414: 415: 416: 417: 418: 419: 420: 421: 422: 423: 424: 425: 426: 427: 428: 429: 430: 431: 432: 433: 434: 435: 436: 437: 438: 439: 440: 441: 442: 443: 444: 445: 446: 447: 448: 449: 450: 451: 452: 453: 454: 455: 456: 457: 458: 459: 460: 461: 462: 463: 464: 465: 466: 467: 468: 469: 470: 471: 472: 473: 474: 475: 476: 477: 478: 479: 480: 481: 482: 483: 484: 485: 486: 487: 488: 489: 490: 491: 492: 493: 494: 495: 496: 497: 498: 499: 500: 501: 502: 503: 504: 505: 506: 507: 508: 509: 510: 511: 512: 513: 514: 515: 516: 517: 518: 519: 520: 521: 522: 523: 524: 525: 526: 527: 528: 529: 530: 531: 532: 533: 534: 535: 536: 537: 538: 539: 540: 541: 542: 543: 544: 545: 546: 547: 548: 549: 550: 551: 552: 553: 554: 555: 556: 557: 558: 559: 560: 561: 562: 563: 564: 565: 566: 567: 568: 569: 570: 571: 572: 573: 574: 575: 576: 577: 578: 579: 580: 581: 582: 583: 584: 585: 586: 587: 588: 589: 590: 591: 592: 593: 594: 595: 596: 597: 598: 599: 600: 601: 602: 603: 604: 605: 606: 607: 608: 609: 610: 611: 612: 613: 614: 615: 616: 617: 618: 619: 620: 621: 622: 623: 624: 625: 626: 627: 628: 629: 630: 631: 632: 633: 634: 635: 636: 637: 638: 639: 640: 641: 642: 643: 644: 645: 646: 647: 648: 649: 650: 651: 652: 653: 654: 655: 656: 657: 658: 659: 660: 661: 662: 663: 664: 665: 666: 667: 668: 669: 670: 671: 672: 673: 674: 675: 676: 677: 678: 679: 680: 681: 682: 683: 684: 685: 686: 687: 
<?php
    declare(strict_types=1);
    /**
     *  +------------------------------------------------------------+
     *  | apnscp                                                     |
     *  +------------------------------------------------------------+
     *  | Copyright (c) Apis Networks                                |
     *  +------------------------------------------------------------+
     *  | Licensed under Artistic License 2.0                        |
     *  +------------------------------------------------------------+
     *  | Author: Matt Saladna (msaladna@apisnetworks.com)           |
     *  +------------------------------------------------------------+
     */

    /**
     * Billing and referral module
     *
     * @package core
     */
    class Billing_Module extends Module_Skeleton implements \Opcenter\Contracts\Hookable
    {
        // @ignore
        private static $BILLING_SERVER_HOST = BILLING_HOST;
        private static $BILLING_SERVER_USER = BILLING_USER;
        private static $BILLING_SERVER_PASSWORD = BILLING_PASSWORD;
        private static $BILLING_SERVER_DATABASE = BILLING_DB;

        /**
         * Recognized preferences in [change,get]_payout_preferences
         * tender:   tender method
         * freeze:   account frozen
         * balance:  credit hosting balance
         *
         * @var array
         */
        private static $_PAYOUT_OPTIONS = array('tender', 'freeze', 'balance');

        /**
         * void __construct(void)
         *
         * @ignore
         */
        public function __construct()
        {
            parent::__construct();

            $this->exportedFunctions = array(
                '*'                       => PRIVILEGE_SITE,
                'add_referral'            => PRIVILEGE_ADMIN,
                'get_invoice_from_domain' => PRIVILEGE_ADMIN,
                'get_package_by_invoice'  => PRIVILEGE_ADMIN,

                /** necessary for sanity checks */
                'get_invoice'             => PRIVILEGE_ALL
            );
        }

        /**
         * Get current payment method
         *
         * @return null|string current payment method, enum: [credit, check, paypal, cash, other]
         */
        public function get_payment_method(): ?string
        {
            return 'other';

        }

        /**
         * Next payment date and amount for the account
         *
         * Array fields-
         * date:   date of next payment for account.  In the event the
         *         information cannot be found (reseller account for example),
         *         -1 is returned.
         * amount: amount for next payment
         *
         * @return array
         */
        public function get_next_payment(): array
        {
            return [
                'date'   => -1,
                'amount' => 0
            ];
        }

        /**
         * array list_payments
         *
         * Sample response:
         * Array
         * (
         *  [0] => Array
         *  (
         *      [date] => 1469937612
         *      [amount] => 65.00
         *      [service] => Webhosting->Developer
         *      [number] => C-2ALQUJ67SSQXIDJEESZFRMZ
         *      [note] =>
         *      [type] => credit
         *  )
         * )
         *
         * @return array
         */
        public function list_payments(): array
        {
            $recs = [];

            return $recs;

        }

        /**
         * Fetch billing status from backend billing server
         *
         * @param string $invoice
         * @return int
         */
        public function get_billing_status(string $invoice = ''): int
        {
            return $this->get_status($invoice);
        }

        /**
         * int get_standing_status()
         *
         * Fetch recurring subscription status from billing server
         *
         *  1  - subscription in good standing
         * -1 - subscription cancelled, account within 90 days of expiring
         * 0  - subscription cancelled, account outside 90 days of expiring
         * null - cannot find subscription
         *
         * @param string $invoice
         * @return int
         */
        public function get_status(string $invoice = ''): ?int
        {
            return 1;
        }

        /**
         * bool is_billed()
         *
         * @return bool billing record exists
         */
        public function is_billed(): bool
        {
            return (bool)$this->get_hosting_subscription();
        }

        /**
         * Currently active subscription number attached to invoice
         *
         * @return mixed|NULL
         */
        public function get_hosting_subscription(): ?string
        {
            return $this->getConfig('billing', 'invoice');
        }

        /**
         * Account was referred by another
         *
         * @param $invoice
         * @return bool
         */
        public function is_referred(string $invoice): bool
        {
            return false;
        }

        /**
         * array get_payment_information(string)
         *
         * Sample response:
         * Array
         * (
         *  [date] => 1469937612
         *  [amount] => 65
         *  [domain] => apnscp.com
         *  [service_level] => Developer
         *  [name] => Tark Sammons
         *  [email] => tark.sammons@apnscp.com
         *  [note] =>
         *  [service_type] => Webhosting
         *  [method] => recurring
         *  [payment_method] => credit
         *  [reference] => C-2ALQUJ67SSQXIDJEESZFRMZ
         *  [txn_id] => 11111
         *  [invoice] => APNSCP-CJKFHECZO35
         *  [cc_type] => visa
         *  [cc_number] => 1111
         *  [cc_exp] => 03/20
         * )
         *
         * @param string $transnum transaction number
         * @param int    $date     unix timestamp of date of transaction
         * @param string $type     payment method type
         * @return array
         */
        public function get_payment_information(string $transnum, int $date, string $type = 'paypal'): array
        {
            return [];
        }

        /**
         * Update profile information
         *
         * @param array $credentials
         * @return bool
         */
        public function edit_referral_profile(array $credentials): bool {
            return error('not implemented');
        }

        /**
         * Check if referral profile exists
         *
         * @return bool
         */
        public function referral_profile_exists(): bool
        {
            return false;
        }

        /**
         * Get referral username
         *
         * @return string|null
         */
        public function get_referral_username(): ?string
        {
            return null;
        }

        /**
         * Set minimum balance for a payout
         *
         * @param float $amount
         * @return bool
         */
        public function edit_payout_amount(float $amount): bool
        {
            return error('not implemented');
        }

        /**
         * float get_payout_amount()
         *
         * @return float|null
         */
        public function get_payout_amount(): ?float
        {
            return null;
        }

        /**
         * float get_minimum_payout_amount
         *
         * @return float
         */
        public function get_minimum_payout_amount(): float
        {
            return (float)self::PAYOUT_MINBAL;
        }

        /**
         * Get current referral balance
         *
         * @return float
         */
        public function referral_balance(): float
        {
            return 0;
        }

        /**
         * Get multiplier used in commission credit
         *
         * @return float
         */
        public function referral_multiplier(): float
        {
            return 1;
        }

        /**
         * Minimum requirement for next referral level
         * array(2) {
         *    ["method"] => 254
         *  ["client"] => 2
         * }
         *
         * @return array
         */
        public function referral_upgrade_needed(): array
        {
            $next = array('method' => 'client', 'next' => 2);

            return $next;
        }

        /**
         * Get earned commissions
         *
         * Sample response
         * array(1) {
         * [0]=>
         * array(5) {
         * ["domain"]=>
         * string(8) "apnscp.com"
         * ["accrued"]=>
         * string(5) "30.00"
         * ["level"]=>
         * string(5) "Basic"
         * ["maturity"]=>
         * int(1172293200)
         * ["status"]=>
         * NULL
         * }
         *
         * domain  (string):
         * accrued (float)
         *
         * @return array
         *
         */

        public function get_referrals(): array
        {
            return [];
        }

        /**
         * array get_customer_referral_information()
         *
         * @return null|array
         */
        public function get_customer_referral_information(): ?array
        {
            return null;
        }

        /**
         * Create initial referral profile
         *
         * @param string $username
         * @param array $personal credentials
         *
         * @return bool
         */
        public function create_referral_profile(string $username, array $personal = []): bool {
            return error('not implemented');
        }

        /**
         * Change referral payout options
         *
         * @param string $pref preference ['frozen', 'tender']
         * @param mixed  $val  payment preference ['paypal', 'check']
         * @return bool
         */
        public function change_payout_preference(string $pref, string $val): bool
        {
            return error('not implemented');
        }

        /**
         * Fetch payout option
         *
         * @param  string $pref preference
         * @return string|null
         */
        public function get_payout_preference(string $pref): ?string
        {
            return null;
        }

        /**
         * Record a new referral
         *
         * @param string $invoice  new account invoice
         * @param string $pinvoice parent invoice (referral profile)
         * @return bool
         */
        public function add_referral(string $invoice, string $pinvoice): bool
        {
            return error('not implemented');
        }

        /**
         * Get referral credit by invoice
         *
         * @param string $invoice
         * @return float|null
         */
        public function get_credit_from_invoice(string $invoice): ?float
        {
            return 0;
        }

        /**
         * Get referral credit by package type
         *
         * @param string $package package type
         * @return float
         */
        public function get_credit_from_package_type(string $package): float
        {
            return 1;
        }

        /**
         * Get hosting invoice by domain
         *
         * @param string $domain domain name
         * @return string|null
         */
        public function get_invoice_from_domain(string $domain): ?string
        {
            return null;
        }

        /**
         * Retrieve latest billing renewal hash for service
         *
         * @return string|null
         */
        public function get_renewal_hash(string $invoice = null): ?string
        {
            return null;
        }

        /**
         * Get billing renewal link
         *
         * Link must provide direct access to billing portal
         *
         * @param string|null $invoice leave blank for current outstanding invoice
         * @return string
         */
        public function get_renewal_link(string $invoice = null): ?string
        {
            return null;
        }

        /**
         * Get customer since
         *
         * @return int unix timestamp or -1 for connectivity issues
         */
        public function get_customer_since(): int
        {
            return (int)($this->getConfig('billing', 'ctime') ??
                filectime($this->domain_fs_path()));
        }

        /**
         * Get billing information attached to account
         *
         * Array
         * (
         *  [first_name] => Tark
         *  [last_name] => Sammons
         *  [city] => Atlanta
         *  [state] => Georgia
         *  [zip_code] => 30308
         *  [country] => US
         *  [company] =>
         *  [address] => 123 Anywhere St
         *  [phone] => 867-5309
         *  [email] => tark.sammons@apnscp.com
         * )
         *
         * @return array
         */
        public function get_billing_information(): array
        {
            return array();
        }

        /**
         * Get billing details
         *
         * @return array|false
         */
        public function get_credit_card_information()
        {
            return [];
        }

        /**
         * Update billing details
         *
         * @param int $expyear
         * @param int $expmonth
         * @param string|null $cvm cvm number, with or without leading zeroes
         * @param int|null $number
         * @param string|null $type
         * @return bool
         */
        public function change_credit_card_information(
            int $expyear,
            int $expmonth,
            ?string $cvm = null,
            ?string $number = null,
            string $type = null
        ): bool {
            return error('not implemented');
        }

        /**
         * Update billing information on account
         *
         * @param string      $firstname
         * @param string      $lastname
         * @param string|null $company
         * @param string      $address
         * @param string      $city
         * @param string      $state
         * @param string      $zip
         * @param string      $country
         * @param string|null $phone
         * @param string|null $email
         * @return bool
         */
        public function change_billing_information(array $details): bool {
            return error('not implemented');
        }

        /**
         * Get current package
         *
         * @return string|null
         */
        public function get_package_type(): ?string
        {
            $invoice = $this->get_invoice();

            return $this->get_package_by_invoice($invoice);
        }

        /**
         * Get package name from invoice
         *
         * @param $invoice
         * @return mixed|null
         */
        public function get_package_by_invoice(string $invoice): ?string
        {
            if ($invoice === $this->get_invoice()) {
                return $this->getServiceValue('siteinfo', 'plan');
            }

            $ids = \Auth::get_site_id_from_invoice($invoice);
            if (null === $ids) {
                return null;
            }

            foreach ($ids as $siteid) {
                $ctx = \Auth::context(null, "site${siteid}");
                if ($ctx->conf->cur['billing']['invoice'] === $invoice) {
                    return $ctx->conf->cur['siteinfo']['plan'] ?? null;
                }
            }

            return null;
        }

        /**
         * Claim referral from token
         *
         * @param  $token string 40 character hash
         * @return bool
         */
        public function claim_referral(string $token): bool
        {
            return error('not implemented');
        }

        /**
         * Get data about a referral
         * Sample return:
         *  Array(
         *      [domain] => apnscp.com
         *      [revenue] => 20.00
         *      [maturity] => 1469937612
         *  )
         *
         * @param string $token
         * @return array|bool
         */
        public function claim_metadata(string $token)
        {
            return error('not implemented');
        }

        /**
         * Used by TemplateEngine to confirm module is setup
         *
         * @return bool
         */
        public function configured(): bool
        {
            return static::class !== self::class;
        }

        public function _verify_conf(\Opcenter\Service\ConfigurationContext $ctx): bool
        {
            return true;
        }

        public function _create()
        {
            // TODO: Implement _create() method.
        }

        public function _delete()
        {
            // TODO: Implement _delete() method.
        }

        public function _edit()
        {
            // TODO: Implement _edit() method.
        }

        public function _create_user(string $user)
        {
            // TODO: Implement _create_user() method.
        }

        public function _delete_user(string $user)
        {
            // TODO: Implement _delete_user() method.
        }

        public function _edit_user(string $userold, string $usernew, array $oldpwd)
        {
            // TODO: Implement _edit_user() method.
        }

        /**
         * Get all invoices
         *
         * @return array
         */
        private function get_all_invoices(): array
        {
            $invoice = (array)$this->get_invoice();
            if (!$invoice) {
                return [];
            }
            $addons = (array)$this->getConfig('billing', 'addons');
            if (!$addons) {
                return $invoice;
            }

            return array_merge($invoice, $addons);
        }

        /**
         * Invariant invoice tied to an account
         *
         * @return null|string
         */
        public function get_invoice(): ?string
        {
            if ($this->permission_level & (PRIVILEGE_ADMIN | PRIVILEGE_RESELLER)) {
                return null;
            }
            $invoice = (string)$this->getConfig('billing', 'invoice');
            if ($invoice) {
                return $invoice;
            }
            if ($this->getConfig('billing', 'parent_invoice')) {
                return (string)$this->getConfig('billing', 'parent_invoice');
            }

            return null;
        }


    }