<?php

use WHMCS\Module\Addon\Proxycheap\AdminWidget;
use WHMCS\Database\Capsule as DB;
use WHMCS\Module\Addon\ProxyCheap\BillingCyclesHelper;

add_hook('AfterShoppingCartCheckout', 1, function ($vars) {
  if ($vars['Addons']) {
    foreach ($vars['Addons'] as $key => $addon_id) {

      $a = DB::table('tblhostingaddons AS ha')
        ->join('tblmodule_configuration AS c', 'ha.addonid', '=', 'c.entity_id')
        ->join('tbladdons AS a', 'a.id', '=', 'ha.addonid')
        ->where('c.entity_type', 'addon')
        ->where('c.setting_name', 'configoption1')
        ->where('c.value', 'ADDON_EXTENSION')
        ->where('a.module', 'proxycheap')
        ->where('ha.id', $addon_id)
        ->first(['ha.addonid', 'ha.hostingid']);
      if ($a) {
        $cf = WHMCS\CustomField::addonFields($a->addonid)->where('fieldname', 'LIKE', 'proxyid%')->first();

        $customFieldValue = WHMCS\CustomField\CustomFieldValue::firstOrNew(["fieldid" => $cf->id, "relid" => $addon_id]);
        $customFieldValue->value = $_SESSION['proxycheap']['addons'][$a->addonid][count($_SESSION['proxycheap']['addons'][$a->addonid]) - 1]['proxy_id'];
        $customFieldValue->save();
        array_pop($_SESSION['proxycheap'][$a->addonid]);
      }

    }
    unset($_SESSION['proxycheap']);
  }
});

add_hook('ClientAreaPageCart', 1, function ($vars) {

  if ($vars['action'] == 'confproduct') {
    if ($vars['productinfo']['module'] === 'proxycheap') {
      unset($_SESSION['cart']['products'][$_GET['i']]);
      header('Location: proxies.php?pid=' . $vars['productinfo']['pid']);
      exit;
    }
  }
});


add_hook('AdminHomeWidgets', 1, function () {
  return new WHMCS\Module\Addon\ProxyCheap\AdminWidget();
});

