<?php

namespace App\Http\Controllers\Esme;

use App\AuditTrail;
use App\DataTables\EsmeCreditHistoryDataTable;
use App\Http\Controllers\Controller;
use App\Tools\SmsTools;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Response;
use Intervention\Image\Facades\Image;

class DashboardController extends Controller
{

    public function index() {
        $role = auth()->user()->role->name;
        if(strtolower($role) !== 'esme')
            return 'You are currently logged as '.$role.', kindly logout before accessing this page';
        return view('esme.welcome');
    }

    public function get_user_log_summary(Request $request) {
        $type = $request['type'];

        $user = Auth::user();
        $username = $user->username;

        $date = Carbon::now();
        $from_date = Carbon::parse($date->toDateString());
        $to_date = clone $from_date;
        $to_date = Carbon::parse($to_date->addDays(1)->addSeconds(-1));

        if($type == 'month') {
            $from_date = $from_date->setDate($from_date->year, $from_date->month, 1);
            $to_date = Carbon::parse($from_date->copy()->addMonth()->addSeconds(-1));
            $dash_title = 'Monthly Dashboard';
        } else if($type == 'week') {
            $from_date = $this->get_weekly_start_day();
            $to_date = $this->get_weekly_end_day();
            $dash_title = 'Weekly Dashboard';
        } else {
            $date = $this->get_date_by_day_name($type);
            $from_date->setDate($date->year, $date->month, $date->day);
            $to_date->setDate($date->year, $date->month, $date->day);
            $dash_title = ucfirst($this->get_day_full_name($type)).' \'s Dashboard';
        }
        if (empty($type)) {
            $date = $this->get_date_by_day_name($type);
            $from_date->setDate($date->year, $date->month, $date->day);
            $to_date->setDate($date->year, $date->month, $date->day);
            $dash_title = ucfirst($type).'Today Dashboard';
        }

        $conn   = DB::connection('kannel');

        $data = $conn->select("select
 CASE SUBSTRING(status,11,7)
   WHEN 'ACK_MAS' THEN 'ACK'
   WHEN 'ED_BY_B' THEN 'ACK'
   WHEN '' THEN 'TOTAL'
   ELSE SUBSTRING(status,11,7)
   END AS stat
  , count(username) as t
from logs
where username=?
and (submit_date between ? and ?)
GROUP BY stat", [$user->username, $from_date, $to_date]);

        $tempArray = [];
        foreach ($data as $dat) {
            $status = $dat->stat;
            $total = $dat->t;
            $tempArray["{$status}"] = $total;
        }

        $total_sms_delivered = isset($tempArray['DELIVRD']) ? $tempArray['DELIVRD']: 0;
        $total_sms_ack = isset($tempArray['ACK']) ? $tempArray['ACK'] : 0;
        $total_sms_undelivered = isset($tempArray['UNDELIV']) ? $tempArray['UNDELIV'] : 0;
        $total_sms_expired = isset($tempArray['EXPIRED']) ? $tempArray['EXPIRED'] : 0;
        $total_sms_rejected = isset($tempArray['REJECTD']) ? $tempArray['REJECTD'] : 0;
        $total_sent = $total_sms_delivered + $total_sms_rejected + $total_sms_ack + $total_sms_undelivered + $total_sms_expired;

        SmsTools::sync_esme_credit($user);

        return [
            'dash_title' => $dash_title,
            'total_sms_sent' => $total_sent,
            'total_sms_delivered' => $total_sms_delivered,
            'total_sms_ack' => $total_sms_ack,
            'total_sms_undelivered' => $total_sms_undelivered,
            'total_sms_expired' => $total_sms_expired,
            'total_balance' => SmsTools::round_currency((!empty($user->credit) ? $user->credit->new_bal:0)),
        ];
    }

    public function get_user_profile() {
        return view('account.profile', ['user'=>Auth::user()]);
    }

    public function get_credit_history(EsmeCreditHistoryDataTable $dataTable) {
        return $dataTable->render('esme.credit_history');
    }

    public function download_receipt($id) {
        $record = Auth::user()->creditHistory()->findOrFail($id);
//        return view('print.payment_receipt', ['record' => $record]);
        $pdf = PDF::loadView('print.payment_receipt', ['record' => $record]);
        return $pdf->download('receipt.pdf');
    }

    public function post_user_profile(Request $request) {
        if($request->has('btnPassword')) {
            //update password
            $this->validate($request, [
                'current_password' => 'required',
                'new_password' => 'required|min:6',
                'confirm_password' => 'same:new_password'
            ]);

            //TODO: check current password
            if (Hash::check($request['current_password'], $request->user()->getAuthPassword())) {
                $user = $request->user();
                $user->password = bcrypt($request['new_password']);
                $user->pass = $request['new_password'];
                $user->must_change_password = false;
                $user->save();

                $request->session()->flash('success', 'Your password has been successfully updated!');
            } else {
                return redirect()->back()->withInput()->withErrors(array('error' => 'Your current password is invalid'));
            }
        } else {
            //update user detail
            $this->validate($request, [
                'first_name' => 'required',
                'last_name' => 'required',
                'organisation' => 'present',
                'picture' => 'file',
                'phone_number' => 'required',
                'website_url' => 'present'
            ]);

            $inputs = $request->except(['picture']);
            $inputs['full_name'] = $inputs['last_name'].' '.$inputs['first_name'];
            $request->user()->update($inputs);

            //update picture
            if(!empty($request['picture'])) {
                $file = Input::file('picture');
                $img = Image::make($file)->resize(400, 400);
                Response::make($img->encode('jpeg'));
                if(empty($request->user()->picture)) {
                    $request->user()->picture()->create(['picture'=>$img]);
                } else {
                    $request->user()->picture()->update(['picture'=>$img]);
                }

            }

            $request->session()->flash('success', 'Your details have been successfully updated!');
        }
        return redirect()->back();
    }

    public function get_traffic_performance_data(Request $request) {
        $user = Auth::user();
        $conn   = DB::connection('kannel');
        $returnvalue = [];
        $returnvalue[] = ['Count', 'Delivered', 'Undelivered','Acknowledged','Expired'];
        $type = $request['type'];

        if($type!='month') {
            //process for day of week
            $data = $conn->select("select
 LEFT(submit_date,10) AS sentAt,
 CASE SUBSTRING(status,11,7)
   WHEN 'ACK_MAS' THEN 'ACK'
   WHEN 'ED_BY_B' THEN 'ACK'
   ELSE SUBSTRING(status,11,7)
   END AS stat
  , count(username) as t
from logs
where username=?
and (submit_date between DATE_SUB(CURDATE(),INTERVAL 7 DAY)  and DATE_ADD(CURDATE(), INTERVAL 1 DAY))
GROUP BY sentAt,stat", [$user->username]);

            $main = [];
            $cdate = '';
            $tempArray = [];
            foreach ($data as $dat) {
                $status = $dat->stat;
                $total = $dat->t;
                $tempArray["{$status}"] = $total;
                if($cdate != $dat->sentAt) {
                    if(!empty($cdate)) {
                        $main["$cdate"] = $tempArray;
                        $tempArray = [];
                    }
                    $cdate = $dat->sentAt;
                }
            }
            $main["$cdate"] = $tempArray;

            foreach ($main as $key => $tempArray) {
                $returnvalue[] = [
                    $this->get_day_name(Carbon::parse($key)),
                    isset($tempArray['DELIVRD']) ? $tempArray['DELIVRD'] : 0,
                    isset($tempArray['UNDELIV']) ? $tempArray['UNDELIV'] : 0,
                    isset($tempArray['ACK']) ? $tempArray['ACK'] : 0,
                    isset($tempArray['EXPIRED']) ? $tempArray['EXPIRED'] : 0
                ];
            }
        } else {
            //process for month
            $now = Carbon::now();
            for($i=1; $i<=5; $i++) {
                $to_date = SmsTools::get_end_of_week($now->year, $now->month, $i);
                $from_date = SmsTools::get_start_of_week($to_date);

                $data = $conn->select("select
 CASE SUBSTRING(status,11,7)
   WHEN 'ACK_MAS' THEN 'ACK'
   WHEN 'ED_BY_B' THEN 'ACK'
   WHEN '' THEN 'TOTAL'
   ELSE SUBSTRING(status,11,7)
   END AS stat
  , count(username) as t
from logs
where username=?
and (submit_date between ? and ?)
GROUP BY stat", [$user->username, $from_date, $to_date]);

                $tempArray = [];
                foreach ($data as $dat) {
                    $status = $dat->stat;
                    $total = $dat->t;
                    $tempArray["{$status}"] = $total;
                }

                $returnvalue[] = [
                    "Week $i",
                    isset($tempArray['DELIVRD']) ? $tempArray['DELIVRD'] : 0,
                    isset($tempArray['UNDELIV']) ? $tempArray['UNDELIV'] : 0,
                    isset($tempArray['ACK']) ? $tempArray['ACK'] : 0,
                    isset($tempArray['EXPIRED']) ? $tempArray['EXPIRED'] : 0
                ];
            }
        }

        return $returnvalue;
    }

    private function get_weekly_start_day() {
        $date = Carbon::now()->setTime(0, 0, 0);
        while (!$date->isMonday()) {
            $date = $date->addDays(-1);
        }
        return $date;
    }

    private function get_weekly_end_day() {
        $date = Carbon::now()->setTime(23, 59, 59);
        while (!$date->isSunday()) {
            $date = $date->addDays(1);
        }
        return $date;
    }

    private function get_date_by_day_name($day_name) {
        $now = Carbon::now()->addDays(-1);
        switch ($day_name) {
            case 'sun':
                while(!$now->isSunday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'mon':
                while(!$now->isMonday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'tue':
                while(!$now->isTuesday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'wed':
                while(!$now->isWednesday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'thu':
                while(!$now->isThursday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'fri':
                while(!$now->isFriday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            case 'sat':
                while(!$now->isSaturday()) {
                    $now = $now->addDays(-1);
                }
                return $now;
            default:
                return $now->addDays(1);
        }
    }

    private function get_day_name(Carbon $date) {
        if($date->isMonday()) {
            return "Mon";
        }
        if($date->isTuesday()) {
            return "Tue";
        }
        if($date->isWednesday()) {
            return "Wed";
        }
        if($date->isThursday()) {
            return "Thu";
        }
        if($date->isFriday()) {
            return "Fri";
        }
        if($date->isSaturday()) {
            return "Sat";
        }
        if($date->isSunday()) {
            return "Sun";
        }
        return "Unknown";
    }

    private function get_day_full_name($day)
    {
        $day = strtolower($day);

        switch ($day)
        {
            case 'sun':
                return 'Sunday';
                break;
            case 'mon':
                return 'Monday';
                break;
            case 'tue':
                return 'Tuesday';
                break;
            case 'wed':
                return 'Wednesday';
                break;
            case 'thu':
                return 'Thursday';
                break;
            case 'fri':
                return 'Friday';
                break;
            case 'sat':
                return 'Saturday';
                break;
            default:
                return 'N / A';
                break;
        }
    }

    public function get_user_picture($id) {
        $record = User::findOrFail($id);
        if(empty($record->picture)) {
            //Image file is stored under project/public/global/portrait/5.jpg
            $file= public_path('global/portraits/17.jpg');

            $headers = array(
                'Content-Type: image/jpeg',
            );

            return Response::download($file, '17.jpg', $headers);
        }
        $pic = Image::make($record->picture->picture);
        $response = Response::make($pic->encode('jpeg'));
        $response->header('Content-Type', 'image/jpeg');
        return $response;
    }

    public function goto_main_route() {
        return redirect()->route('esme.app');
    }

    public function logout() {
        $user = Auth::user();

        AuditTrail::create([
            'user_id' => $user->id,
            'username' => $user->username,
            'date' => \Carbon\Carbon::now()->toDateTimeString(),
            'activity' => $user->name.' logged out '
        ]);

        Auth::logout();
        return redirect()->route('esme.login');
    }
}
