<?php

namespace Mtc\Modules\BasketRecovery\Classes;

use Basket;
use Illuminate\Support\Facades\App;

/**
 * BasketRecoveryEmail class
 *
 * Used to generate the email for the BasketRecovery plugin
 *
 * @author  Craig McCreath <craig.mccreath@mtcmedia.co.uk>
 */
class BasketRecoveryEmail
{
    public static $replace_tags = [
        '{customer_name}',
    ];

    /**
     * Generate the email for the basket provided
     * 
     * @param  int              $basket_id
     * @param  BasketRecovery   $recovery
     * @param  array            $coupon    Coupon Data
     * @return string           Generated HTML
     */
    public static function generateEmailForBasketId($basket_id, BasketRecovery $recovery, $coupon = '')
    {
        $twig = App::make('twig');
        $basket = new Basket($basket_id);
        $basket->resetSession();
        $basket->Go_Basket(true);

        $html = $twig->render('Modules/BasketRecovery/email_body.twig', [
            'items' => $basket->items,
            'coupon' => $coupon,
            'recovery' => $recovery,
            'recovery_url' => $recovery->button_url ?: self::generateRecoveryUrl($basket, $recovery->id),
            'recovery_read_url' => $recovery->button_url ?: self::generateRecoveryUrl($basket, $recovery->id, 'read.gif'),
        ]);

        return self::formatEmailLinks(str_replace(
            self::$replace_tags,
            [
                $basket->address['billing']['firstname'],
            ],
            $html
        ), $recovery->id);
    }


    /**
     * Append tracking ID to urls
     *
     * @param $text
     * @param $recovery_id
     * @return mixed
     */
    public static function formatEmailLinks($text, $recovery_id)
    {
        $preg_pattern = "/<a\s[^>]*href=([\"\']??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU";

        return preg_replace_callback(
            $preg_pattern, function ($m) use ($recovery_id) {
            $sub = stripslashes($m[0]);
            $start_link = (strpos($sub, "href=") + 6);
            $end_link = strpos(substr($sub, $start_link, (strlen($sub) - $start_link)), "\"");
            $left_html = substr($sub, 0, $start_link);
            $right_html = substr($sub, ($start_link + $end_link));
            $link = substr($sub, $start_link, $end_link);
            $link .= (strpos($link, '?') === false ? '?' : '&') . 'fup_id=' . $recovery_id;
            return $left_html . $link . $right_html;

        }, $text);
    }


    /**
     * Generate the URL which we should return the user to
     * 
     * @param  Basket $basket
     * @param  int    $recovery_id BasketRecorvery->id
     * @param  string $suffix_url  A suffix - used if sending this URL
     *                             to another file in this folder (e.g. read.gif)
     * @return string
     */
    public static function generateRecoveryUrl(Basket $basket, $recovery_id, $suffix_url = '')
    {
        $params = [
            'id' => $basket->id,
            'recovery_id' => $recovery_id,
            'hash' => self::generateRecoveryHash($basket->id.'_'.$recovery_id),
        ];

        return SITE_URL . BasketRecovery::getBasePath().'/recovery/'.$suffix_url.'?'.http_build_query($params);
    }

    /**
     * Generate a hash for a simple security check.
     * @param  mixed    $input    Text Input
     * @return string   Hashed string
     */
    public static function generateRecoveryHash($input)
    {
        return sha1(BasketRecovery::HASH . $input);
    }
}
