<commit_before><?php

require_once('Billing.php');
define('VAT_RATE', 19.00);

class BillingController extends Zend_Controller_Action {

    public function init()
    {       
        //Two of the actions in this controller return JSON because they're used for AJAX:
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('vat-validator', 'json')
                    ->addActionContext('promo-eligibility-check', 'json')
                    ->addActionContext('is-country-in-eu', 'json')
                    ->initContext();
    }
    
    public function indexAction()
    {
        $this->_redirect('billing/upgrade');
    }

    public function promoEligibilityCheckAction()
    {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $request = $this->getRequest();
        if (!$request->isPost()) {
            throw new Exception("Must POST data to promoEligibilityCheckAction.");
        }
        $data = $request->getPost();

        $current_namespace = new Zend_Session_Namespace('csrf_namespace');
        $observed_csrf_token = $this->_getParam('csrf_token');
        $expected_csrf_token = $current_namespace->authtoken;

        if($observed_csrf_token == $expected_csrf_token) {
            $eligible = Billing::isClientEligibleForPromo(
                $data["newproductid"], $data["newproductbillingcycle"]);

            //Set the return JSON value
            $this->_helper->json(array("result"=>$eligible));
        } else {
            $this->getResponse()->setHttpResponseCode(403);
            $this->_helper->json(array("result"=>false, "error"=>"CSRF token did not match."));
        }
    }

    public function upgradeAction()
    {
        $CC_CONFIG = Config::getConfig();
        $baseUrl = Application_Common_OsPath::getBaseDir();
        $this->view->headLink()->appendStylesheet($baseUrl.'css/billing.css?'.$CC_CONFIG['airtime_version']);
        Billing::ensureClientIdIsValid();
        
        $request = $this->getRequest();
        $form = new Application_Form_BillingUpgradeDowngrade();

        if ($request->isPost()) {
                        
            $formData = $request->getPost();

            if ($form->isValid($formData)) {

                // Check if client is eligible for promo and update the new product id if so
                $eligibleForPromo = Billing::isClientEligibleForPromo(
                    $formData["newproductid"], $formData["newproductbillingcycle"]);
                if ($eligibleForPromo) {
                    $newProductName = Billing::getProductName($formData["newproductid"]);
                    $formData["newproductid"] = Billing::getEligibleAwesomeAugustPromoPlanId($newProductName);
                }

                $credentials = Billing::getAPICredentials();

                //Check if VAT should be applied or not to this invoice.
                if (in_array("7", $formData["customfields"])) {
                    $apply_vat = Billing::checkIfVatShouldBeApplied($formData["customfields"]["7"], $formData["country"]);
                } else {
                    $apply_vat = false;
                }

                $placeAnUpgradeOrder = true;

                $currentPlanProduct = Billing::getClientCurrentAirtimeProduct();
                $currentPlanProductId = $currentPlanProduct["pid"];
                $currentPlanProductBillingCycle = strtolower($currentPlanProduct["billingcycle"]);
                //If there's been no change in the plan or the billing cycle, we should not
                //place an upgrade order. WHMCS doesn't allow this in its web interface,
                //and it freaks out and does the wrong thing if we do it via the API
                //so we have to do avoid that.
                if (($currentPlanProductId == $formData["newproductid"]) &&
                    ($currentPlanProductBillingCycle == $formData["newproductbillingcycle"])
                ) {
                    $placeAnUpgradeOrder = false;
                }

                $postfields = array();
                $postfields["username"] = $credentials["username"];
                $postfields["password"] = <PASSWORD>($credentials["password"]);
                $postfields["action"] = "upgradeproduct";
                $postfields["clientid"] = Application_Model_Preference::GetClientId();

                $postfields["serviceid"] = Billing::getClientInstanceId();
                $postfields["type"] = "product";
                $postfields["newproductid"] = $formData["newproductid"];
                $postfields["newproductbillingcycle"] = $formData["newproductbillingcycle"];
                $postfields["paymentmethod"] = $formData["paymentmethod"];
                $postfields["responsetype"] = "json";

                $upgrade_query_string = "";
                foreach ($postfields AS $k => $v) $upgrade_query_string .= "$k=" . urlencode($v) . "&";

                //update client info

                $clientfields = array();
                $clientfields["username"] = $credentials["username"];
                $clientfields["password"] = <PASSWORD>($credentials["password"]);
                $clientfields["action"] = "updateclient";
                $clientfields["clientid"] = Application_Model_Preference::GetClientId();
                $clientfields["customfields"] = base64_encode(serialize($formData["customfields"]));
                unset($formData["customfields"]);
                $clientfields["responsetype"] = "json";
                unset($formData["newproductid"]);
                unset($formData["newproductbillingcycle"]);
                unset($formData["paymentmethod"]);
                unset($formData["action"]);
                $clientfields = array_merge($clientfields, $formData);
                unset($clientfields["password2verify"]);
                unset($clientfields["submit"]);
                $client_query_string = "";
                foreach ($clientfields AS $k => $v) $client_query_string .= "$k=" . urlencode($v) . "&";

                //Update the client details in WHMCS first
                $result = Billing::makeRequest($credentials["url"], $client_query_string);
                Logging::info($result);
                if ($result["result"] == "error") {
                    $this->setErrorMessage();
                    $this->view->form = $form;
                    return;
                }

                //If there were no changes to the plan or billing cycle, we just redirect you to the
                //invoices screen and show a message.
                if (!$placeAnUpgradeOrder) {
                    $this->_redirect('billing/invoices?planupdated');
                    return;
                }

                //Then place an upgrade order in WHMCS
                $result = Billing::makeRequest($credentials["url"], $upgrade_query_string);
                if ($result["result"] == "error") {
                    Logging::info($_SERVER['HTTP_HOST'] . " - Account upgrade failed. - " . $result["message"]);
                    $this->setErrorMessage();
                    $this->view->form = $form;
                } else {
                    Logging::info($_SERVER['HTTP_HOST'] . "Account plan upgrade request:");
                    Logging::info($result);

                    // Disable the view and the layout here, squashes an error.
                    $this->view->layout()->disableLayout();
                    $this->_helper->viewRenderer->setNoRender(true);

                    if ($apply_vat) {
                        Billing::addVatToInvoice($result["invoiceid"]);
                    }
                    self::viewInvoice($result["invoiceid"]);
                }
            } else {
                $this->view->form = $form;
            }
        } else {
            $this->view->form = $form;
        }
    }
    
    
    public function isCountryInEuAction()
    {
        // Disable the view and the layout
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
 
        $request = $this->getRequest();
        if (!$request->isPost()) {
            throw new Exception("Must POST data to isCountryInEuAction.");<commit_msg>Fix for bringing customer to view invoice that doesn't exist after downgrade<commit_after><?php

require_once('Billing.php');
define('VAT_RATE', 19.00);

class BillingController extends Zend_Controller_Action {

    public function init()
    {       
        //Two of the actions in this controller return JSON because they're used for AJAX:
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('vat-validator', 'json')
                    ->addActionContext('promo-eligibility-check', 'json')
                    ->addActionContext('is-country-in-eu', 'json')
                    ->initContext();
    }
    
    public function indexAction()
    {
        $this->_redirect('billing/upgrade');
    }

    public function promoEligibilityCheckAction()
    {
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $request = $this->getRequest();
        if (!$request->isPost()) {
            throw new Exception("Must POST data to promoEligibilityCheckAction.");
        }
        $data = $request->getPost();

        $current_namespace = new Zend_Session_Namespace('csrf_namespace');
        $observed_csrf_token = $this->_getParam('csrf_token');
        $expected_csrf_token = $current_namespace->authtoken;

        if($observed_csrf_token == $expected_csrf_token) {
            $eligible = Billing::isClientEligibleForPromo(
                $data["newproductid"], $data["newproductbillingcycle"]);

            //Set the return JSON value
            $this->_helper->json(array("result"=>$eligible));
        } else {
            $this->getResponse()->setHttpResponseCode(403);
            $this->_helper->json(array("result"=>false, "error"=>"CSRF token did not match."));
        }
    }

    public function upgradeAction()
    {
        $CC_CONFIG = Config::getConfig();
        $baseUrl = Application_Common_OsPath::getBaseDir();
        $this->view->headLink()->appendStylesheet($baseUrl.'css/billing.css?'.$CC_CONFIG['airtime_version']);
        Billing::ensureClientIdIsValid();
        
        $request = $this->getRequest();
        $form = new Application_Form_BillingUpgradeDowngrade();

        if ($request->isPost()) {
                        
            $formData = $request->getPost();

            if ($form->isValid($formData)) {

                // Check if client is eligible for promo and update the new product id if so
                $eligibleForPromo = Billing::isClientEligibleForPromo(
                    $formData["newproductid"], $formData["newproductbillingcycle"]);
                if ($eligibleForPromo) {
                    $newProductName = Billing::getProductName($formData["newproductid"]);
                    $formData["newproductid"] = Billing::getEligibleAwesomeAugustPromoPlanId($newProductName);
                }

                $credentials = Billing::getAPICredentials();

                //Check if VAT should be applied or not to this invoice.
                if (in_array("7", $formData["customfields"])) {
                    $apply_vat = Billing::checkIfVatShouldBeApplied($formData["customfields"]["7"], $formData["country"]);
                } else {
                    $apply_vat = false;
                }

                $placeAnUpgradeOrder = true;

                $currentPlanProduct = Billing::getClientCurrentAirtimeProduct();
                $currentPlanProductId = $currentPlanProduct["pid"];
                $currentPlanProductBillingCycle = strtolower($currentPlanProduct["billingcycle"]);
                //If there's been no change in the plan or the billing cycle, we should not
                //place an upgrade order. WHMCS doesn't allow this in its web interface,
                //and it freaks out and does the wrong thing if we do it via the API
                //so we have to do avoid that.
                if (($currentPlanProductId == $formData["newproductid"]) &&
                    ($currentPlanProductBillingCycle == $formData["newproductbillingcycle"])
                ) {
                    $placeAnUpgradeOrder = false;
                }

                $postfields = array();
                $postfields["username"] = $credentials["username"];
                $postfields["password"] = <PASSWORD>($credentials["password"]);
                $postfields["action"] = "upgradeproduct";
                $postfields["clientid"] = Application_Model_Preference::GetClientId();

                $postfields["serviceid"] = Billing::getClientInstanceId();
                $postfields["type"] = "product";
                $postfields["newproductid"] = $formData["newproductid"];
                $postfields["newproductbillingcycle"] = $formData["newproductbillingcycle"];
                $postfields["paymentmethod"] = $formData["paymentmethod"];
                $postfields["responsetype"] = "json";

                $upgrade_query_string = "";
                foreach ($postfields AS $k => $v) $upgrade_query_string .= "$k=" . urlencode($v) . "&";

                //update client info

                $clientfields = array();
                $clientfields["username"] = $credentials["username"];
                $clientfields["password"] = <PASSWORD>($<PASSWORD>["password"]);
                $clientfields["action"] = "updateclient";
                $clientfields["clientid"] = Application_Model_Preference::GetClientId();
                $clientfields["customfields"] = base64_encode(serialize($formData["customfields"]));
                unset($formData["customfields"]);
                $clientfields["responsetype"] = "json";
                unset($formData["newproductid"]);
                unset($formData["newproductbillingcycle"]);
                unset($formData["paymentmethod"]);
                unset($formData["action"]);
                $clientfields = array_merge($clientfields, $formData);
                unset($clientfields["password2verify"]);
                unset($clientfields["submit"]);
                $client_query_string = "";
                foreach ($clientfields AS $k => $v) $client_query_string .= "$k=" . urlencode($v) . "&";

                //Update the client details in WHMCS first
                $result = Billing::makeRequest($credentials["url"], $client_query_string);
                Logging::info($result);
                if ($result["result"] == "error") {
                    $this->setErrorMessage();
                    $this->view->form = $form;
                    return;
                }

                //If there were no changes to the plan or billing cycle, we just redirect you to the
                //invoices screen and show a message.
                if (!$placeAnUpgradeOrder) {
                    $this->_redirect('billing/invoices?planupdated');
                    return;
                }

                //Then place an upgrade order in WHMCS
                $result = Billing::makeRequest($credentials["url"], $upgrade_query_string);
                if ($result["result"] == "error") {
                    Logging::info($_SERVER['HTTP_HOST'] . " - Account upgrade failed. - " . $result["message"]);
                    $this->setErrorMessage();
                    $this->view->form = $form;
                } else {
                    Logging::info($_SERVER['HTTP_HOST'] . "Account plan upgrade request:");
                    Logging::info($result);

                    // Disable the view and the layout here, squashes an error.
                    $this->view->layout()->disableLayout();
                    $this->_helper->viewRenderer->setNoRender(true);

                    if ($apply_vat) {
                        Billing::addVatToInvoice($result["invoiceid"]);
                    }

                    // invoice id can be 0 if client is downgrading and they don't
                    // owe any money
                    if (!empty($result["invoiceid"])) {
                        self::viewInvoice($result["invoiceid"]);
                    }
                }
            } else {
                $this->view->form = $form;
            }
        } else {
            $this->view->form = $form;
        }
    }
    
    
    public function isCountryInEuAction()
    {
        // Disable the view and the layout
        $this->view->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
 
        $request = $this->getRequest();
        if (!$request->isPost()) {
            throw new Exception("Must POST data to isCountryInEuAction.");
{'fraction_non_alphanumeric': 0.13252654683514267, 'fraction_numerical': 0.0014830634157916593, 'mean_word_length': 1.965869106263195, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 130, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5560329', 'n_tokens_mistral': 4475, 'n_tokens_neox': 4174, 'n_words': 825}