<?php
class DashboardController extends \BaseController
{
    private function chartMonth()
    {
        $month = DB::table('installments')
            ->whereRaw('year(`in_date`) = ?', [date('Y')])
            ->select(
                DB::raw('MONTHNAME(in_date) as month'),
                DB::raw('DAYOFMONTH(in_date) as d'),
                DB::raw('year(in_date) as y'),
                DB::raw("DATE_FORMAT(in_date,'%Y-%m') as monthNum"),
                'in_date'
            )
            ->groupBy('month')->orderBy('in_date', 'asc')->get();
        return $month;
    }

    public function getIndex()
    {
      
        $installments = Installment::customers()
                           ->select(
                            'installments.*',
                            'lc.full_name_kh',
                            'lc.full_name_en',
                            'lc.gender',
                            'lc.tel'
                            )->orderBy('installments.created_at', 'desc')
                           ->take(5)->get();
        $chartData = [
            'month' => [],
            'expense' => [],
            'priciple' => [],
            'income' => [],
            'rate' => []
        ];
          
        if (get_config('dashboard_chart') == 'yes') {
            foreach ($this->chartMonth() as $expense) {
                $chartData['month'][] = $expense->month;
                $chartData['expense'][] = Profit::monthly($expense->in_date);
                $chartData['priciple'][] = Payment::byMonth($expense->in_date);
                $chartData['rate'][] = Payment::byMonth($expense->in_date, 'rate');
            }
        }
        
        $saleSoFar = Profit::getSaleSoFar();
        $totalExpense = Profit::getTotalExpense();
        $todayExpense = Profit::where("type", "expense")->whereBetween("created_at", [$this->startToday(), $this->endToday()])->sum('amount');
        $totalDeposit = Installment::whereBetween('created_at', [$this->startToday(), $this->endToday()])
                              ->where('deposit', '>', 0)->sum('deposit');
        $totalAmount = get_payment('total', [
            'start' => $this->startToday(),
            'end' => $this->endToday()
        ]);
        
        $totalLate = get_payment('late', [
            'start' => $this->startToday(),
            'end' => $this->endToday()
        ]);
        $totalPriciple = get_payment('principal', [
            'start' => $this->startToday(),
            'end' => $this->endToday()
        ]);

        $totalInterest = get_payment('interest', [
            'start' => $this->startToday(),
            'end' => $this->endToday()
        ]);
        $totalPaidPrincipal =  0;
        
        // $totalPaidPrincipal = get_config("show_remain_principal") == "yes" ? get_payment('principal', []) : 0;
        // return dd(get_payment('principal', []));
        
        $monthlyExpense = Profit::where("type", 'expense')->whereBetween("created_at", [$this->startThisMonth(), $this->endThisMonth()])->sum('amount');
        $monthlyPrincipal = get_payment("principal", [
            'start' => $this->startThisMonth(),
            'end' => $this->endThisMonth()
        ]);
        
        $monthlyInterest = get_payment("interest", [
            'start' => $this->startThisMonth(),
            'end' => $this->endThisMonth()
        ]);
        $monthlyLate = get_payment("late", [
            'start' => $this->startThisMonth(),
            'end' => $this->endThisMonth()
        ]);
        $payments = MortgagePayment::mortgagePayments([
            'start' => $this->startToday(),
            'end' => $this->endToday()
        ]);
        
        $todayPrincipal = 0;
        $todayInterest = 0;
        
        foreach ($payments as $payment) {
            $totalPayment = ($payment->total_amount < $payment->amount) && $payment->is_paid_interest == false ? $payment->total_amount : $payment->amount;
            $paidPrincipal = $payment->is_paid_interest ? 0 : $payment->principal;
            $todayPrincipal += $paidPrincipal;
            $interest = ($payment->total_amount < $payment->amount) && $payment->is_paid_interest == false ? $payment->amount - $payment->total_amount : $payment->interest;
            $todayInterest += $interest;
        }
        
        $todayTotal = $todayInterest + $todayPrincipal;
        $monthlyPayments = MortgagePayment::mortgagePayments([
            'start' => $this->startThisMonth(),
            'end' => $this->endThisMonth()
        ]);
        $totalMp = MortgagePayment::mortgagePayments([]);
        $tmp = 0;
        foreach ($totalMp as $mp) {
            $paidPrincipal = $mp->is_paid_interest ? 0 : $mp->principal;
            $tmp += $paidPrincipal;
        }
        
        foreach ($monthlyPayments as $payment) {
            $totalPayment = ($payment->total_amount < $payment->amount) && $payment->is_paid_interest == false ? $payment->total_amount : $payment->amount;
            $paidPrincipal = $payment->is_paid_interest ? 0 : $payment->principal;
            $monthlyPrincipal += $paidPrincipal;
            $interest = ($payment->total_amount < $payment->amount) && $payment->is_paid_interest == false ? $payment->amount - $payment->total_amount :    $payment->interest;
            $monthlyInterest += $interest;
        }
        
        return View::make('dashboard.dashboard')
                ->with("monthlyExpense", $monthlyExpense)
                ->with("monthlyPrincipal", $monthlyPrincipal)
                ->with("monthlyInterest", $monthlyInterest)
                ->with("monthlyLate", $monthlyLate)
                ->with('saleSoFar', $saleSoFar)
                ->with('totalExpense', $totalExpense)
                ->with("todayExpense", $todayExpense)
                ->withInstallments($installments)
                ->withTotalLate($totalLate)
                ->with('chartData', $chartData)
                ->withTotalRate($totalInterest + $todayInterest)
                ->withTotalDeposit($totalDeposit)
                ->withTotalPriciple($totalPriciple + $todayPrincipal)
                ->withGrandTotal($totalAmount + $totalLate + $todayTotal)
                ->with('totalPaidPrincipal', $totalPaidPrincipal + $tmp);
    }

    public function localKey()
    {
        return Hash::make(Helper::checkApp());
    }

    public function updateThumbnailUrl()
    {
        $products = Product::all();
        foreach ($products as $product) {
            Product::find($product->id)->update(['thumbnail' => Config::get('app.ip') . 'uploads/products/' . $product->thumbnail]);
        }
    }

    private function startThisMonth()
    {
        $startThisMonth = Carbon\Carbon::now();
        return $startThisMonth->startOfMonth();
    }

    private function endThisMonth()
    {
        $endThisMonth = Carbon\Carbon::now();
        return $endThisMonth->endOfMonth();
    }

    private function startToday()
    {
        $startToday = Carbon\Carbon::today();
        return $startToday;
    }

    private function endToday()
    {
        $endToday = Carbon\Carbon::today();
        $endToday->addHours(23)
            ->addMinutes(59)
            ->addSeconds(59);
        return $endToday;
    }
}
