<?php
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Mail;


function getCards()
{
    return \App\Models\Card::where('enabled', true)->orderBy('name')->get();
}

function getCategories()
{
    return \App\Models\Category::where('enabled', true)->where('parent_id', null)->orderBy('name')->get();
}

function formatPrice($price)
{
    return "€ " . number_format($price, 2, ",", ".");
}

function getVatValue($v, $i)
{
    $vat = 0;
    //if (env('VAT_MANAGE', 0) == 1)
    //{
        $vats = \App\Models\Vat::select('id', 'name', 'value')->orderBy('value')->get();

        if ($i > 0)
        {
            $iv = 0;
            foreach($vats as $vv)
            {
                if ($vv->id == $i)
                {
                    $iv = $vv->value;
                    break;
                }
            }
            if ($iv > 0)
                $vat = $v / 100 * $iv;
        }
    //}
    return $vat;
}

function mysqlToDate($dt)
{
    list($date, $hour) = explode(" ", $dt);
    list($year, $month, $day) = explode("-", $date);
    return $day . "/" . $month . "/" . $year;
}


function currencyToDouble($val)
{
    $x = str_replace("€", "", $val);
    $x = str_replace(".", "", $x);
    $x = str_replace(",", ".", $x);
    return floatval(trim($x));
}

function getConfiguration($field)
{
    $ret = "";
    $conf = \App\Models\Configuration::first();
    if ($conf)
    {
        $ret = $conf[$field];
    }
    return $ret;
}

function sendReceiptEmail($receipt)
{
    $pdf = PDF::loadView('receipt', array('receipt' => $receipt));
    $pdfName = "Ricevuta_" . $receipt->member->last_name . "_" . $receipt->number . "_" . $receipt->year . ".pdf";
    //$pdfName = "Ricevuta_" . $receipt->number . "_" . $receipt->year . ".pdf";
    Storage::put('public/pdf/' . $pdfName, $pdf->output());
    $email = '';
    $member = \App\Models\Member::findOrFail($receipt->member_id);
    if ($member->no_send_mail == null || !$member->no_send_mail)
    {
        if ($member->isAdult())
            $email = $member->email;
        else
        {
            $check = explode(" ", $member->father_name);
            if (str_contains($receipt->parent, $check[0]))
            {
                $email = $member->father_email;
            }
            else
            {
                $check = explode(" ", $member->mother_name);
                if (str_contains($receipt->parent, $check[0]))
                    $email = $member->mother_email;
            }
        }
        if ($email != '')
        {
            try
            {
                $ragione_sociale = "";
                $azienda = \App\Models\Azienda::first();
                if ($azienda) {
                    $ragione_sociale = $azienda->ragione_sociale;
                }

                Mail::to($email)->bcc(env('MAIL_CCN', ''))->send(new \App\Mail\ReceipEmail([
                    'pdf' => 'public/pdf/' . $pdfName,
                    'number' => $receipt->number . "/" . $receipt->year,
                    'ragione_sociale' => $ragione_sociale,
                ]));
            } catch (Exception $e) {
                //echo 'Caught exception: ',  $e->getMessage(), "\n";
            }
        }
    }
}

function sendReceiptDeleteEmail($receipt)
{
    $pdf = PDF::loadView('receipt', array('receipt' => $receipt));
    $pdfName = "Ricevuta_annullata_" . $receipt->member->last_name . "_" . $receipt->number . "_" . $receipt->year . ".pdf";
    Storage::put('public/pdf/' . $pdfName, $pdf->output());
    $email = '';
    $member = \App\Models\Member::findOrFail($receipt->member_id);
    if ($member->no_send_mail == null || !$member->no_send_mail)
    {
        if ($member->isAdult())
            $email = $member->email;
        else
        {
            $check = explode(" ", $member->father_name);
            if (str_contains($receipt->parent, $check[0]))
            {
                $email = $member->father_email;
            }
            else
            {
                $check = explode(" ", $member->mother_name);
                if (str_contains($receipt->parent, $check[0]))
                    $email = $member->mother_email;
            }
        }
        if ($email != '')
        {
            try
            {
                $ragione_sociale = "";
                $azienda = \App\Models\Azienda::first();
                if ($azienda) {
                    $ragione_sociale = $azienda->ragione_sociale;
                }

                Mail::to($email)->bcc(env('MAIL_CCN', ''))->send(new \App\Mail\ReceipDeleteEmail([
                    'number' => $receipt->number . "/" . $receipt->year,
                    'pdf' => 'public/pdf/' . $pdfName,
                    'date' => date("d/m/Y", strtotime($receipt->date)),
                    'ragione_sociale' => $ragione_sociale,
                ]));
            } catch (Exception $e) {
                //echo 'Caught exception: ',  $e->getMessage(), "\n";
            }
        }
    }
}

function updateMemberData($member_id)
{
    $member = \App\Models\Member::findOrFail($member_id);
    $status = $member->getStatus();
    $status = $status["status"];
    $has_certificate = $member->hasCertificate();
    $certificate = 0;
    $certificate_date = null;
    if($has_certificate["date"] != '')
    {
        if($has_certificate["date"] < date("Y-m-d"))
            $certificate = 0;

        if($has_certificate["date"] >= date("Y-m-d") && $has_certificate["date"] < date("Y-m-d", strtotime("+1 month")))
            $certificate = 1;

        if($has_certificate["date"] >= date("Y-m-d", strtotime("+1 month")))
            $certificate = 2;

        $certificate_date = $has_certificate["date"] != '' ? $has_certificate["date"] : null;
    }

    $member->current_status = $status;
    $member->certificate = $certificate;
    $member->certificate_date = $certificate_date;
    $member->save();
}

function getMonthName($m, $short = false)
{
    $ret = '';
    switch ($m) {
        case 1:
            $ret = $short ? ' Gen' : 'Gennaio';
            break;
        case 2:
            $ret = $short ? ' Feb' : 'Febbraio';
            break;
        case 3:
            $ret = $short ? ' Mar' : 'Marzo';
            break;
        case 4:
            $ret = $short ? ' Apr' : 'Aprile';
            break;
        case 5:
            $ret = $short ? ' Mag' : 'Maggio';
            break;
        case 6:
            $ret = $short ? ' Giu' : 'Giugno';
            break;
        case 7:
            $ret = $short ? ' Lug' : 'Luglio';
            break;
        case 8:
            $ret = $short ? ' Ago' : 'Agosto';
            break;
        case 9:
            $ret = $short ? ' Set' : 'Settembre';
            break;
        case 10:
            $ret = $short ? ' Ott' : 'Ottobre';
            break;
        case 11:
            $ret = $short ? ' Nov' : 'Novembre';
            break;
        case 12:
            $ret = $short ? ' Dic' : 'Dicembre';
            break;
        default:
            $ret = '';
            break;
    }
    return $ret;
}

function getMonthList()
{
    $months = [];
    if (env('FISCAL_YEAR_MONTH_FROM', 1) > 1)
    {
        for($x=env('FISCAL_YEAR_MONTH_FROM', 1); $x<=12; $x++)
        {
            $months[$x] = getMonthName($x);
        }
        for($x=1; $x<env('FISCAL_YEAR_MONTH_FROM', 1); $x++)
        {
            $months[$x] = getMonthName($x);
        }
    }
    else
    {
        for($x=1; $x<=12; $x++)
        {
            $months[$x] = getMonthName($x);
        }
    }
    return $months;
}

function sms_send($params, $backup = false)
{
    static $content;

    if ($backup == true) {
        $url = 'https://api2.smsapi.com/sms.do';
    } else {
        $url = 'https://api.smsapi.com/sms.do';
    }

    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, $url);
    curl_setopt($c, CURLOPT_POST, true);
    curl_setopt($c, CURLOPT_POSTFIELDS, $params);
    curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($c, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer " . env('SMS_TOKEN', 'kHebe4eQ5cTbPCHGiGrNJAFsy2z0fiF3W7DdO8Ss')
    ));

    $content = curl_exec($c);
    $http_status = curl_getinfo($c, CURLINFO_HTTP_CODE);

    if ($http_status != 200 && $backup == false) {
        $backup = true;
        sms_send($params, $token, $backup);
    }

    curl_close($c);
    return $content;
}
