<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Barryvdh\DomPDF\Facade\Pdf;
use App\Models\Member;
use App\Http\Middleware\TenantMiddleware;
use Illuminate\Support\Facades\DB;


class Rate extends Component
{
    public $records;

    public $member_id = 0;
    public $member_course_id = 0;
    public $member_subscription_id = 0;
    public $rate_from = 'course';

    public $mc = null;
    public $ms = null;

    public $filterStatus = '';
    public $hasFilter = false;
    public $filterFrom = '', $filterTo = '';
    public $filteredMemberId = '';
    public $members = [];
    public $detail = '';

    public $course_subscription_id;
    public $price;
    public $date;
    public $month = '';
    public $months = [];
    public $disabled = [];
    public $course_subscriptions = [];
    public $price_list = [];
    public $type = '';

    public $errorMsg = '';

    public function boot()
    {
        app(TenantMiddleware::class)->setupTenantConnection();
    }

    protected function setupTenantConnection()
    {
        $user = auth()->user();

        config(['database.connections.tenant' => [
            'driver' => 'mysql',
            'host' => '127.0.0.1',
            'port' => '3306',
            'database' => $user->tenant_database,
            'username' => $user->tenant_username,
            'password' => $user->tenant_password,
        ]]);

        config(['database.default' => 'tenant']);
        DB::purge('tenant');
        DB::reconnect('tenant');
    }

    public function mount()
    {
        // Load members for the dropdown
        $this->member_id = isset($_GET["member_id"]) ? $_GET["member_id"] : 0;
        $this->member_course_id = isset($_GET["member_course_id"]) ? $_GET["member_course_id"] : 0;

        if ($this->member_id > 0 && $this->member_course_id > 0)
        {
            $this->mc = \App\Models\MemberCourse::findOrFail($this->member_course_id);
            $this->detail = $this->mc->course->getDetailsName() . "<br/>" .  $this->mc->member->first_name . " " . $this->mc->member->last_name;

            $this->price_list = [];
            $c = $this->mc->course;
            if ($c->prices != null)
            {
                foreach(json_decode($c->prices) as $z)
                {
                    $this->price_list[$z->course_subscription_id] = $z->price;
                }
            }

            $course_subscription_ids = [];
            if ($c->prices != null) {
                foreach (json_decode($c->prices) as $z) {
                    if ($z->price > 0)
                        $course_subscription_ids[] = $z->course_subscription_id;
                }
            }

            $this->course_subscriptions = \App\Models\CourseSubscription::select('*')->whereIn('id', $course_subscription_ids)->where('enabled', true)->get();

            $this->rate_from = 'course';
        }

        $this->member_subscription_id = isset($_GET["member_subscription_id"]) ? $_GET["member_subscription_id"] : 0;
        if ($this->member_id > 0 && $this->member_subscription_id > 0)
        {
            $this->ms = \App\Models\MemberSubscription::findOrFail($this->member_subscription_id);
            $this->detail = $this->ms->subscription->name . "<br/>" .  $this->ms->member->first_name . " " . $this->ms->member->last_name;

            $this->price_list = [];
            $s = $this->ms->subscription;
            if ($s->prices != null)
            {
                foreach(json_decode($s->prices) as $z)
                {
                    $this->price_list[$z->course_subscription_id] = $z->price;
                }
            }

            $course_subscription_ids = [];
            if ($s->prices != null) {
                foreach (json_decode($s->prices) as $z) {
                    if ($z->price > 0)
                        $course_subscription_ids[] = $z->course_subscription_id;
                }
            }

            $this->course_subscriptions = \App\Models\CourseSubscription::select('*')->whereIn('id', $course_subscription_ids)->where('enabled', true)->get();
            
            $this->rate_from = 'subscription';
        }
    }

    public function render()
    {
        if ($this->member_id > 0 && $this->member_course_id > 0) {
            $this->records = \App\Models\Rate::with('member')->where('member_course_id', $this->member_course_id)->where('member_id', $this->member_id)->orderBy('date')->get();
        } elseif ($this->member_id > 0 && $this->member_subscription_id > 0) {
            $this->records = \App\Models\Rate::with('member')->where('member_subscription_id', $this->member_subscription_id)->where('member_id', $this->member_id)->orderBy('date')->get();
        }

        $this->disabled = [];
        foreach($this->records as $r)
        {
            foreach (json_decode($r->months) as $m) {
                $this->disabled[] = $m;
            }
        }

        return view('livewire.rate');
    }

    public function updatedCourseSubscriptionId()
    {
        $this->price = 0;
        if (isset($this->price_list[$this->course_subscription_id]))
            $this->price = $this->price_list[$this->course_subscription_id];

        $this->type = '';
        if ($this->course_subscription_id > 0)
            $this->type = \App\Models\CourseSubscription::findOrFail($this->course_subscription_id)->months;
    }

    public function add()
    {

        $this->errorMsg = '';
        if ($this->date == '')
        {
            $this->errorMsg = 'La data di scadenza è obbligatoria';
        }
        else
        {

            if (!$this->course_subscription_id > 0)
            {
                $this->errorMsg = 'Devi selezionare un tipo di abbonamento';
            }
            else
            {

                if ($this->type > 1 && $this->type < sizeof($this->months)) {
                    // $this->errorMsg = 'Hai selezionato un numero di mesi errato in base all\'abbonamento selezionato' . $this->type .'.'. sizeof($this->months);
                    $this->errorMsg = 'Mesi selezionati superiori a quelli previsti dall’abbonamento';
                } elseif ($this->type == 1 && !$this->month) {
                    $this->errorMsg = 'Seleziona un mese';
                } else {
                    $rate = new \App\Models\Rate();
                    $rate->member_id = $this->member_id;
                    $rate->member_course_id = $this->member_course_id > 0 ? $this->member_course_id : null;
                    $rate->member_subscription_id = $this->member_subscription_id > 0 ? $this->member_subscription_id : null;
                    $rate->course_subscription_id = $this->course_subscription_id;
                    $rate->price = currencyToDouble($this->price);
                    $rate->date = $this->date;
                    if ($this->type == '1')
                        $this->months[] = $this->month;
                    $rate->months = json_encode($this->months);
                    $rate->note = '';
                    $rate->status = 0;
                    $rate->save();

                    $this->course_subscription_id = null;
                    $this->price = 0;
                    $this->date = null;
                    $this->month = '';
                    $this->months = [];

                    $this->emit('close-popup');
                }
            }

        }

    }

    public function printReceipt($id)
    {
        $this->emit('load-data-table');
        $receipt = \App\Models\Receipt::findOrFail($id);
        //$pdf = PDF::loadView('pdf/receipt', array('datas' => $datas, 'from' => $x, 'to' => $y, 'who' => '', 'matricola' => $matricola));
        $pdf = PDF::loadView('receipt', array('receipt' => $receipt));//->output();
        return $pdf->stream('aaa.pdf');

    }

    public function search()
    {
        $this->hasFilter = true;
    }

    public function disableSearch()
    {
        $this->filterStatus = "";
        $this->filterTo = '';
        $this->filterFrom = '';
        $this->filteredMemberId = '';
        $this->hasFilter = false;
    }

    public function delete($id)
    {
        try{
            \App\Models\Rate::find($id)->delete();
            //$this->emit('load-data-table');
            session()->flash('success',"Rata eliminata");
        }catch(\Exception $e){
            session()->flash('error','Errore (' . $e->getMessage() . ')');
        }
    }

    public function deleteMultiple($ids)
    {
        try{
            foreach($ids as $id)
            {
                \App\Models\Rate::find($id)->delete();
            }
            //$this->emit('load-data-table');
            session()->flash('success',"Rata eliminata");
        }catch(\Exception $e){
            session()->flash('error','Errore (' . $e->getMessage() . ')');
        }
    }

    public function suspendMultiple($ids)
    {
        try{
            foreach($ids as $id)
            {
                $r = \App\Models\Rate::find($id);
                $r->status = $r->status == 2 ? 0 : 2;
                $r->save();
            }

            //$this->emit('load-data-table');
            session()->flash('success',"Rata eliminata");
        }catch(\Exception $e){
            session()->flash('error','Errore (' . $e->getMessage() . ')');
        }
    }

    public function addDeleteMonth($m)
    {
        if (!in_array($m, $this->months)) {
            $this->months[] = $m;
        } else {
            if (($key = array_search($m, $this->months)) !== false) {
                unset($this->months[$key]);
                $this->months = array_values($this->months);
            }
        }
    }
}
