<?php

namespace ModulesGarden\HostingQuotaNotifications\App\Helper;

use ModulesGarden\HostingQuotaNotifications\App\Libs\TicketTemplatesLangs\Manage;
use \ModulesGarden\HostingQuotaNotifications\Core\ModuleConstants;
use ModulesGarden\HostingQuotaNotifications\App\Helper\SmartyHelper\Product;
use ModulesGarden\HostingQuotaNotifications\App\Helper\SmartyHelper\Domain;
use ModulesGarden\HostingQuotaNotifications\App\Helper\SmartyHelper\Invoice;
use ModulesGarden\HostingQuotaNotifications\App\Helper\SmartyHelper\Ticket;
use ModulesGarden\HostingQuotaNotifications\App\Helper\SmartyHelper\Affiliate;
use ModulesGarden\HostingQuotaNotifications\App\Helper\SmartyHelper\Admin;
use ModulesGarden\HostingQuotaNotifications\App\Helper\SmartyHelper\Other;
use ModulesGarden\HostingQuotaNotifications\App\Helper\SmartyHelper\Client;
use ModulesGarden\HostingQuotaNotifications\Core\Models\Whmcs\Client as WHMCSClient;
use ModulesGarden\HostingQuotaNotifications\App\Models\Templates\MessageGroups;
use \ModulesGarden\HostingQuotaNotifications\App\Models\Templates\Templates;

/**
 * Description of TemplatesHelper
 *
 * @author Artur Pilch <artur.pi@modulesgarden.com>
 */
class TemplatesHelper
{
    public static function deleteUsedLangs($allLanguages, $usedLanguages)
    {
        foreach($usedLanguages as $lang)
        {
            unset($allLanguages[$lang->lang]);
        }
        return $allLanguages;
    }

    public static function getUnusedLanguages($templateLangId = false)
    {
        $allLanguages = self::getLanguages();
        $usedLanguages = Manage::getUsedLangsForTemplate(Request::getValue('templateId'), $templateLangId);
        return self::deleteUsedLangs($allLanguages, $usedLanguages);
    }

    public static function getLanguages()
    {
        $whmcsPath    = ModuleConstants::getFullPathWhmcs();
        $dirpath      = $whmcsPath . '/lang/';
        $scanLanguage = scandir($dirpath);
        $avalibleLang = array_diff($scanLanguage, array('.', '..', 'index.php'));
        $langTab      = [];
        $langTab['default'] = 'Default';
        foreach ($avalibleLang as $lang)
        {
            $lang = explode('.', $lang);
            if ($lang[1] == 'php')
            {
                $langTab[$lang[0]] = ucfirst($lang[0]);
            }
        }
        return $langTab;
    }

    public static function getUsedLanguages()
    {
        $model = (new WHMCSClient())
                        ->select("language")
                        ->distinct("language")
                        ->groupby("language")
                        ->get()->toArray();

        $tab             = [];
        $tab['default'] = "Default";
        
        foreach ($model as $lang)
        {
            $tab[$lang['language']] = ucfirst($lang['language']);
        }

        return $tab;
    }

    public static function getUserLang($uid)
    {
        $select = WHMCSClient::select('language')->where('id', $uid)->first();

        $language = $select->language;

        if (!$language)
        {
            $language = DBModelsHelper::getWHMCSConfigValue('language');
            ;
        }

        if (!$language)
        {
            $language = 'english';
        }

        return strtolower($language);
    }


    public static function restoreNotExistingTemplates()
    {
        //TODO insert with activation not existing
    }

    public static function getGroupVariables($group, $relid = null, $message = '')
    {
        
        $out = array();
        $obj = false;
        if ($group == "product")
        {
            $obj = new Product($relid);
        }
        if ($group == "domain")
        {
            $obj = new Domain($relid);
        }
        if ($group == "invoice")
        {
            $obj = new Invoice($relid);
        }
        if ($group == "support")
        {
            $obj = new Ticket($relid, true);
        }
        if ($group == "affiliate")
        {
            $obj = new Affiliate($relid);
        }

        $userid = $relid;
        if ($obj !== false)
        {
            $out    = $obj->getMergeFields();
            $userid = $obj->getUserID();
        }
       
        if ($group == "admin")
        {
            $groups = Admin::getGroupsForMessage($message);
            foreach ($groups as $item)
            {               
                $class = "\ModulesGarden\SmsCenter\App\Helper\SmartyHelper\\" . ucfirst(($item == "service" ? "product" : $item));
                $obj   = new $class($relid[$item]);
                $out   = array_merge($obj->getMergeFields(), $out);
            }
        }

        if ($group != "admin")
        {
            $obj = new Client($userid);
            $out = array_merge($out, $obj->getMergeFields());
        }

        $obj = new Other();
        $out = array_merge($out, $obj->getMergeFields());
        
        return $out;
    }

    public static function getGroupedGroupVariablesNames($group, $message = '')
    {
        $out              = array();
        if ($group == "product")
            $out['product']   = Product::getMergeFieldsNames();
        if ($group == "domain")
            $out['domain']    = Domain::getMergeFieldsNames();
        if ($group == "invoice")
            $out['invoice']   = Invoice::getMergeFieldsNames();
        if ($group == "support")
            $out['support']   = Ticket::getMergeFieldsNames();
        if ($group == "affiliate")
            $out['affiliate'] = Affiliate::getMergeFieldsNames();
        if ($group == "order")
            $out['order']     = Order::getMergeFieldsNames();

        if ($group != "admin")
            $out['client'] = Client::getMergeFieldsNames();
        
        if ($group == "admin")
        {
            $groups = Admin::getGroupsForMessage($message);
            foreach ($groups as $item)
            {
                if ($item == "service")
                    $item                                         = "product";
                $class                                        = "\ModulesGarden\SmsCenter\App\Helper\SmartyHelper\\".ucfirst($item);
                $out[($item == "ticket" ? "support" : $item)] = $class::getMergeFieldsNames();
            }
        }
        $out['other'] = Other::getMergeFieldsNames();
        return $out;
    }

    public static function getGroupVariablesNames($group, $message = '')
    {
        $out = array();
        foreach (self::getGroupedGroupVariablesNames($group, $message) as $g)
        {
            $out = array_merge($out, $g);
        }
        return $out;
    }

    public static function createDefaultTemplatesIfNotExists()
    {
        $templates = self::getDefaultTemplates();
        
        $messageModel = new MessageGroups();
        $templateModel = new Templates();
        foreach($templates as $group =>$names)
        {
            foreach($names as  $name => $template)
            {
                $gid = $messageModel->select("id")->where('group', $group)->where('msg_name', $name)->first();
                $exists = $templateModel->where('group_id', $gid->id)->where('lang','default')->first();
                if(!$exists && $gid->id)
                {
                    $data = [
                        'group_id' =>$gid->id,
                        'lang' => 'default',
                        'message' => $template
                        
                    ];
                    $templateModel->create($data);
                }
            }
        }
    }
    
    public static function getDefaultEmailTemplates($group, $name)
    {
        $templates = self::getDefaultTemplates();
        return $templates[$group][$name];

    }
    
    
    public static function getDefaultTemplates($group = null, $name = null)
    {
        return array(
            'domain'    => array(
                'Expired Domain Notice'            =>
                'The domain{$domain_name} expired {$domain_days_after_expiry} days ago.
Due to the domain expiring, the domain will not be accessible. You can renew it for up to 30 days after the renewal date at: {$whmcs_url}/cart.php?gid=renewals',
                'Domain Registration Confirmation' =>
                'Domain purchase has been successful.

Registration Date: {$domain_reg_date}
Domain: {$domain_name}
Registration Period: {$domain_reg_period}
Amount: {$domain_first_payment_amount}
Next Due Date: {$domain_next_due_date}

Login to manage your domain.

{$whmcs_url}',
                'Domain Renewal Confirmation'      =>
                'Domain renewal request has been completed.

Domain: {$domain_name}
Renewal Length: {$domain_reg_period}
Renewal Price: {$domain_recurring_amount}
Next Due Date: {$domain_next_due_date}

Login to manage your domain.

{$whmcs_url}',
                'Domain Transfer Completed'        =>
                'Domain transfer has been completed.

Order Date: {$domain_reg_date}
Domain: {$domain_name}
Status: {$domain_status}

Login to manage your domain.

{$whmcs_url}',
                'Domain Transfer Initiated'        =>
                'Transfer process has been initiated.  Domain purchase details:

Domain: {$domain_name}
Registration Length: {$domain_reg_period}
Transfer Price: {$domain_first_payment_amount}
Renewal Price: {$domain_recurring_amount}
Next Due Date: {$domain_next_due_date}

Login to manage your domain.

{$whmcs_url}',
                'Upcoming Domain Renewal Notice'   =>
                'At least one of your domains is due to expire soon. To ensure the domain does not expire, you should renew it now from the domains management:
{$whmcs_url}',
                'Domain Transfer Failed'           =>
                'Domain transfer order failed. Please contact us to re-attempt the transfer once the reason is solved.

Domain: {$domain_name}'
            ),
            'affiliate' => array(
                'Affiliate Monthly Referrals Report' =>
                'Monthly affiliate referrals report.

Total Visitors Referred: {$affiliate_total_visits}
Current Earnings: {$affiliate_balance}
Amount Withdrawn: {$affiliate_withdrawn}'
            ),
            'general'   => array(
                'Credit Warning'              =>
                'Your credit balance has gone below minimal credit limit.
Please add some credits or your account will be suspended.',
                'Access Details Reset'        =>
                'Password for {$client_name} has now been reset.

New login details:
Username: {$client_username}
Password: {$client_password}

Login URL: {$whmcs_url}',
                'Automated Password Reset'    =>
                'Password  has been reset.

New login details:
Email: {$client_email}
Password: {$client_password}',
                'Client Signup Email'         =>
                'A new account has been setup.

Login details:
Email Address: {$client_email}
Password: {$client_password}

To login, visit {$whmcs_url}',
                'Credit Card Expiring Soon'   =>
                'Notice!

{$client_cc_type} ending with {$client_cc_number} expires on {$client_cc_expiry}

Update your credit card information ASAP to avoid service intervals!',
                'Order Confirmation'          =>
                'Order confirmation message.

{if $order_number}Order number: {$order_number}{/if}

You will be notified once your account is setup.',
                'Password Reset Confirmation' =>
                'Password has been reset.

If it was not at your request, then please contact support.',
                'Password Reset Reminder'     =>
                'Reminder!

Password should be changed, fill new password here:
{$password_link}

{if $send_access_details}
Login URL: {$password_url}
Username: {$password_username}
Password: {$password_password}
{/if}',
                'Password Reset Validation'   =>
                'Request to reset your password has been submitted.

If you did not request this, please ignore this message.

Login to reset your password:
{$pw_reset_url}',
                'Quote Accepted'              =>
                'Quote has been accepted and invoice for the quote is generated.',
                'Quote Accepted Notification' =>
                'Quote has been accepted.',
                'Customer Information'        =>
                'Customer ID: {$client_id}
Name: {$client_firstname} {$client_lastname} 
Email: {$client_email}
Company: {$client_companyname}
Address 1: {$client_address1}
Address 2: {$client_address2}
City: {$client_city}
State: {$client_state}
Postcode: {$client_postcode}
Country: {$client_country}
Phone Number: {$client_phonenumber}',
                'Quote Delivery with PDF'     =>
                'The quote that you requested has been sent in pdf to your email.',
                'Unsubscribe Confirmation'    =>
                'Your email address has been removed from our mailing list!
Re-subscribe at any time from My Details section.'
            ),
            'invoice'   => array(
                'Credit Card Invoice Created'      =>
                'Invoice {$invoice_num}  has been generated on {$invoice_date_created}.

Payment method: {$invoice_payment_method}
Amount Due: {$invoice_total}
Due Date: {$invoice_date_due}

Payment will be taken automatically from your credit card.',
                'Credit Card Payment Confirmation' =>
                'Credit Card Payment Confirmation

Invoice {$invoice_num} sent on {$invoice_date_created} has been paid.

Amount: {$invoice_last_payment_amount}
Status: {$invoice_status}

Review your invoice details:
{$invoice_link}',
                'Credit Card Payment Due'          =>
                'Invoice Payment Reminder

Invoice {$invoice_num} is due on {$invoice_date_due}.

Invoice Date: {$invoice_date_created}
Amount Due: {$invoice_total}

Please login and make the payment.

{$invoice_link}',
                'Credit Card Payment Failed'       =>
                'Recent credit card payment failed.

Invoice Date: {$invoice_date_created}
Invoice No: {$invoice_num}
Amount: {$invoice_total}
Status: {$invoice_status}

Login to your client area and pay the invoice manually.
{$invoice_link}',
                'First Invoice Overdue Notice'     =>
                'Invoice no. {$invoice_num} generated on {$invoice_date_created} is overdue.

Payment method: {$invoice_payment_method}
Balance Due: {$invoice_balance}
Due Date: {$invoice_date_due}

Login to view and pay the invoice.

{$invoice_link}',
                'Invoice Created'                  =>
                'Invoice has been generated on {$invoice_date_created}.

Payment method: {$invoice_payment_method}

Invoice No: {$invoice_num}
Amount Due: {$invoice_total}
Due Date: {$invoice_date_due}

Login to view and pay the invoice.

{$invoice_link}',
                'Invoice Payment Confirmation'     =>
                'Payment confirmation details for Invoice {$invoice_num} sent on {$invoice_date_created}.

Amount: {$invoice_last_payment_amount}
Transaction #: {$invoice_last_payment_transid}
Total Paid: {$invoice_amount_paid}
Remaining Balance: {$invoice_balance}
Status: {$invoice_status}',
                'Invoice Payment Reminder'         =>
                'Billing reminder!
Invoice no. {$invoice_num} generated on {$invoice_date_created} is due on {$invoice_date_due}.
Payment method: {$invoice_payment_method}
Balance Due: {$invoice_balance}

Login to view and pay the invoice.

{$invoice_link}',
                'Invoice Refund Confirmation'      =>
                'A {if $invoice_status eq "Refunded"}full{else}partial{/if} refund has been processed for Invoice #{$invoice_num}.

Login to review invoice details:

{$invoice_link}',
                'Second Invoice Overdue Notice'    =>
                'Second billing notice! Invoice no. {$invoice_num} generated on {$invoice_date_created} is overdue.

Payment method: {$invoice_payment_method}
Balance Due: {$invoice_balance}
Due Date: {$invoice_date_due}

Login to view and pay the invoice.

{$invoice_link}',
                'Third Invoice Overdue Notice'     =>
                'Third and final billing notice! Invoice no. {$invoice_num} generated on {$invoice_date_created} is overdue. Lack of payment will result in account suspension.

Payment method: {$invoice_payment_method}
Balance Due: {$invoice_balance}
Due Date: {$invoice_date_due}

Login to view and pay the invoice.

{$invoice_link}',
            ),
            'product'   => array(
                'Service Unsuspension Notification'   =>
                'This is a notification that your service has been unsuspended. 
Product/Service: {$service_product_name}
{if $service_domain}Domain: {$service_domain}
{/if}Amount: {$service_recurring_amount}
Due Date: {$service_next_due_date}',
                'Cancellation Request Confirmation'   =>
                'Cancellation request:

Product/Service: {$service_product_name}
Domain: {$service_domain}

{if $service_cancellation_type=="Immediate"}The service will be terminated within 24 hours.{else}The service will be cancelled at the end of your billing period.{/if}',
                'Dedicated/VPS Server Welcome Email'  =>
                'New Dedicated Server you have ordered has been set up and is operational now.

Find more details in the email message.',
                'Hosting Account Welcome Email'       =>
                'Your hosting account has now been setup.

Find more details in the email message.',
                'Other Product/Service Welcome Email' =>
                'Order for {$service_product_name} has been activated.

Payment Method: {$service_payment_method}
Amount: {$service_first_payment_amount}
Billing Cycle: {$service_billing_cycle}
Next Due Date: {$service_next_due_date}',
                'Reseller Account Welcome Email'      =>
                'The reseller hosting account for {$service_domain} has been set up.

Find more details in the email message.',
                'Service Suspension Notification'     =>
                'Your service has been suspended.

Product/Service: {$service_product_name}
{if $service_domain}Domain: {$service_domain}{/if}

Amount: {$service_first_payment_amount}
Due Date: {$service_next_due_date}
Suspension Reason: {$service_suspension_reason}',
                'SHOUTcast Welcome Email'             =>
                'SHOUTcast account has been setup.',
                'New Account Information'             =>
                'Domain: {$service_domain}
Username: {$service_username}
Password: {$service_password}',
                'Server Information'                  =>
                'Server Name: {$service_server_name}
Server IP: {$service_server_ip}
Nameserver 1: {$service_ns1}
Nameserver 1 IP: {$service_ns1_ip}
Nameserver 2: {$service_ns2}
Nameserver 2 IP: {$service_ns2_ip}'
            ),
            'support'   => array(
                'Clients Only Bounce Message'            =>
                'Your email to our support system could not be accepted. Email address was not recognized. If you need assistance, please email from the address that you use to login to client area.',
                'Replies Only Bounce Message'            =>
                'Your email to our support system could not be accepted. Submit all tickets via our online client support portal.

{$whmcs_url}/submitticket.php',
                'Support Ticket Auto Close Notification' =>
                'The status of your ticket #{$ticket_id} has been changed to Closed.

Subject: {$ticket_subject}
Priority: {$ticket_priority}',
                'Closed Ticket Bounce Message'           =>
                'Your email to our ticket system could not be accepted. The ticket has already been closed.
Reopen the ticket at: {$ticket_link}',
                'Support Ticket Feedback Request'        =>
                'Ticket {$ticket_id} request is completed.
We would appreciate it if you let us know about the quality of our service.

{$ticket_url}&feedback=1

Thank you!',
                'Support Ticket Opened'                  =>
                'Support ticket has been opened.

Subject: {$ticket_subject}
Priority: {$ticket_priority}
Status: {$ticket_status}

{$ticket_url}',
                'Support Ticket Opened by Admin'         =>
                'Support ticket opened by Admin.

{$ticket_subject}

{$ticket_message}',
                'Support Ticket Reply'                   =>
                'Support ticket has been replied.

Ticket ID: {$ticket_id}
Subject: {$ticket_subject}
Status: {$ticket_status}
Ticket URL: {$ticket_url}',
            ),
// ADDED IN V1.5
            'admin'     => array(
                'Automatic Setup Failed'               =>
                'An order has received its first payment but the automatic provisioning has failed and requires you to manually check & resolve.

Client ID: {$client_id}
{if $service_id}Service ID: {$service_id}
Product/Service: {$service_product}
Domain: {$service_domain}{else}Domain ID: {$domain_id}
Registration Type: {$domain_type}
Domain: {$domain_name}{/if} 
Find more details in the email message.

{$whmcs_admin_link}',
                'Automatic Setup Successful'           =>
                'An order has received its first payment and the product/service has been automatically provisioned successfully.

Client ID: {$client_id}
{if $service_id}Service ID: {$service_id}
Product/Service: {$service_product}
Domain: {$service_domain}{else}Domain ID: {$domain_id}
Registration Type: {$domain_type}
Domain: {$domain_name}{/if}

{$whmcs_admin_link}',
                'Domain Renewal Failed'                =>
                'An invoice for the renewal of a domain has been paid but the renewal request submitted to the registrar failed.

Client ID: {$client_id}
Domain ID: {$domain_id}
Domain Name: {$domain_name}
Find more details in the email message.

{$whmcs_admin_link}',
                'Domain Renewal Successful'            =>
                'An invoice for the renewal of a domain has been paid and the renewal request was submitted to the registrar successfully.

Client ID: {$client_id}
Domain ID: {$domain_id}
Domain Name: {$domain_name}

{$whmcs_admin_link}',
                'New Cancellation Request'             =>
                'A new cancellation request has been submitted.

Client ID: {$client_id}
Client Name: {$clientname}
Service ID: {$service_id}
Product Name: {$product_name}
Cancellation Type: {$service_cancellation_type}
Cancellation Reason: {$service_cancellation_reason}

{$whmcs_admin_link}',
                'New Order Notification'               =>
                'Order Information

Order ID: {$order_id}
Order Number: {$order_number}
Date/Time: {$order_date}
Invoice Number: {$invoice_id}
Payment Method: {$order_payment_method}

Customer Information

Customer ID: {$client_id}
Name: {$client_first_name} {$client_last_name}
Email: {$client_email}
Company: {$client_company_name}
Address 1: {$client_address1}
Address 2: {$client_address2}
City: {$client_city}
State: {$client_state}
Postcode: {$client_postcode}
Country: {$client_country}
Phone Number: {$client_phonenumber}

ISP Information

IP: {$client_ip}
Host: {$client_hostname}

{$whmcs_admin_url}orders.php?action=view&id={$order_id}',
                'Service Unsuspension Failed'          =>
                'This product/service has received its next payment but the automatic reactivation has failed.

Client ID: {$client_id}
Service ID: {$service_id}
Product/Service: {$service_product}
Domain: {$service_domain}
Find more details in the email message.

{$whmcs_admin_link}',
                'Service Unsuspension Successful'      =>
                'This product/service has received its next payment and has been reactivated successfully.

Client ID: {$client_id}
Service ID: {$service_id}
Product/Service: {$service_product}
Domain: {$service_domain}

{$whmcs_admin_link}',
                'Support Ticket Created'               =>
                'A new support ticket has been opened.

Client: {$client_name}{if $client_id} #{$client_id}{/if} 
Department: {$ticket_department}
Subject: {$ticket_subject}
Priority: {$ticket_priority}

---
{$ticket_message}
---

You can respond to this ticket by simply replying to this email or through the admin area at the url below.

{$whmcs_admin_url}supporttickets.php?action=viewticket&id={$ticket_id}',
                'Support Ticket Department Reassigned' =>
                'The department this ticket is assigned to has been changed to a department you are a member of.

Client: {$client_name}{if $client_id} #{$client_id}{/if} 
Department: {$ticket_department}
Subject: {$ticket_subject}
Priority: {$ticket_priority}

---
{$ticket_message}
---

You can respond to this ticket by simply replying to this email or through the admin area at the url below.

{$whmcs_admin_url}supporttickets.php?action=viewticket&id={$ticket_id}',
                'Support Ticket Flagged'               =>
                'A new support ticket has been flagged to you.

Ticket #: {$ticket_tid}
Client Name: {$client_name} (ID {$client_id})
Department: {$ticket_department}
Subject: {$ticket_subject}
Priority: {$ticket_priority}

----------------------
{$ticket_message}
----------------------

{$whmcs_admin_url}supporttickets.php?action=viewticket&id={$ticket_id}',
                'Support Ticket Response'              =>
                'A new support ticket response has been made.

Client: {$client_name}{if $client_id} #{$client_id}{/if} 
Department: {$ticket_department}
Subject: {$ticket_subject}
Priority: {$ticket_priority}

---
{$ticket_message}
---

You can respond to this ticket by simply replying to this email or through the admin area at the url below.

{$whmcs_admin_url}supporttickets.php?action=viewticket&id={$ticket_id}',
                'Client Login Notification' =>
                'Notification:
{$client_first_name} {$client_first_name} client logged in to the website.'
            )
        );

        
    }
}
