<?php

namespace App\Http\Controllers;

use App\Charts\ConsultationChart;
use App\Charts\SaleChart;
use App\Charts\StockChart;
use App\Models\Code;
use App\Models\Curbatch;
use App\Models\Dompojb;
use App\Models\EID;
use App\Models\Sales;
use App\Models\Stockd;
use App\Models\Type;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;

class DashboardController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $id)
    {
        ini_set('max_execution_time', '-1');
        $user = User::where('name', '=', Auth::user()->name)
            ->where('surname', '=', Auth::user()->surname)->first();

        $eid = EID::where('id', '=', $user->eid_id)->first();
        $name = $eid->schemaName;
        Session::put('connectionName', $eid->enterprise_id);

        $date = Carbon::now();
        $create_date = date('d/m/Y', strtotime($date));
        $array = explode('-', $id);
        $year = $array[0];
        $month = $array[1];
        $month_name = date("F", mktime(0, 0, 0, $month, 10));
        $selected_date = $month_name . ' ' . $year;
        $selected_date2 = $month_name . '-' . $year;


        $quotient = $year % 4;

        // creating line chart
        $consultationChart = new ConsultationChart();

        if ($month == '1' or $month == '3' or $month == '5' or $month == '7' or $month == '8' or $month == '10' or $month == '12') {
            $consultationChart->labels([
                '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15',
                '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'
            ]);
            $days = 31;
        } elseif ($month == '4' or $month == '6' or $month == '9' or $month == '11') {
            $consultationChart->labels([
                '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15',
                '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30'
            ]);
            $days = 30;
        } elseif ($month == '2')
            if ($quotient > 0) {
                $consultationChart->labels([
                    '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15',
                    '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28'
                ]);
                $days = 28;
            } else {
                $consultationChart->labels([
                    '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15',
                    '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29'
                ]);
                $days = 29;
            }
        $sdate = Carbon::createFromFormat('Y-m-d', $year . '-' . $month . '-' . 01);
        $start_date = $sdate->format('Y-m-d', $sdate);
        $edate = Carbon::createFromFormat('Y-m-d', $year . '-' . $month . '-' . $days);
        $end_date = $edate->format('Y-m-d', $edate);
        // $branches = Branch::where('id', '=', $request->branch_id)->get();



        $vetConArray = array();
        for ($i = 1; $i <= $days; $i++) {
            $day = $i;
            $d = Carbon::createFromFormat('Y-m-d', $year . '-' . $month . '-' . $day);
            $date = $d->format('Y-m-d', $d);
            $invoice = DB::select("select invoice_date, itemcat, invnum from $name.invoice where invoice_date = '$date'");

            $count = 0;
            foreach ($invoice as $inv) {
                if ($inv->itemcat != 'C')
                    continue;

                $count = $count + 1;
            }
            $vetConArray[$i] = $count;
        }
        if ($month == '1' or $month == '3' or $month == '5' or $month == '7' or $month == '8' or $month == '10' or $month == '12')
            $consultationChart->dataset('All Daily Consultations', 'line', [
                $vetConArray[1], $vetConArray[2], $vetConArray[3], $vetConArray[4], $vetConArray[5], $vetConArray[6],
                $vetConArray[7], $vetConArray[8], $vetConArray[9], $vetConArray[10], $vetConArray[11], $vetConArray[12],
                $vetConArray[13], $vetConArray[14], $vetConArray[15], $vetConArray[16], $vetConArray[17], $vetConArray[18],
                $vetConArray[19], $vetConArray[20], $vetConArray[21], $vetConArray[22], $vetConArray[23], $vetConArray[24],
                $vetConArray[25], $vetConArray[26], $vetConArray[27], $vetConArray[28], $vetConArray[29], $vetConArray[30],
                $vetConArray[31]
            ])->options([
                'fill' => 'true',
                'borderColor' => '#29BDE1',
                'backgroundColor' => '#1937bf',
            ]);
        elseif ($month == '4' or $month == '6' or $month == '9' or $month == '11')
            $consultationChart->dataset('All Daily Consultations', 'line', [
                $vetConArray[1], $vetConArray[2], $vetConArray[3], $vetConArray[4], $vetConArray[5], $vetConArray[6],
                $vetConArray[7], $vetConArray[8], $vetConArray[9], $vetConArray[10], $vetConArray[11], $vetConArray[12],
                $vetConArray[13], $vetConArray[14], $vetConArray[15], $vetConArray[16], $vetConArray[17], $vetConArray[18],
                $vetConArray[19], $vetConArray[20], $vetConArray[21], $vetConArray[22], $vetConArray[23], $vetConArray[24],
                $vetConArray[25], $vetConArray[26], $vetConArray[27], $vetConArray[28], $vetConArray[29], $vetConArray[30]
            ])->options([
                'fill' => 'true',
                'borderColor' => '#29BDE1',
                'backgroundColor' => '#1937bf',
            ]);
        elseif ($month == '2')
            if ($quotient > 0) {
                $consultationChart->dataset('All Daily Consultations', 'line', [
                    $vetConArray[1], $vetConArray[2], $vetConArray[3], $vetConArray[4], $vetConArray[5], $vetConArray[6],
                    $vetConArray[7], $vetConArray[8], $vetConArray[9], $vetConArray[10], $vetConArray[11], $vetConArray[12],
                    $vetConArray[13], $vetConArray[14], $vetConArray[15], $vetConArray[16], $vetConArray[17], $vetConArray[18],
                    $vetConArray[19], $vetConArray[20], $vetConArray[21], $vetConArray[22], $vetConArray[23], $vetConArray[24],
                    $vetConArray[25], $vetConArray[26], $vetConArray[27], $vetConArray[28]
                ])->options([
                    'fill' => 'true',
                    'borderColor' => '#51C1C0'
                ]);
            } else {
                $consultationChart->dataset('All Daily Consultations', 'line', [
                    $vetConArray[1], $vetConArray[2], $vetConArray[3], $vetConArray[4], $vetConArray[5], $vetConArray[6],
                    $vetConArray[7], $vetConArray[8], $vetConArray[9], $vetConArray[10], $vetConArray[11], $vetConArray[12],
                    $vetConArray[13], $vetConArray[14], $vetConArray[15], $vetConArray[16], $vetConArray[17], $vetConArray[18],
                    $vetConArray[19], $vetConArray[20], $vetConArray[21], $vetConArray[22], $vetConArray[23], $vetConArray[24],
                    $vetConArray[25], $vetConArray[26], $vetConArray[27], $vetConArray[28], $vetConArray[29]
                ])->options([
                    'fill' => 'true',
                    'borderColor' => '#51C1C0'
                ]);
            }
        $consultationChart->options(
            ['scales' => [
                'yAxes' => [
                    [
                        'ticks' => [
                            'suggestedMax' => 50,
                            'beginAtZero' => true,
                            'stepSize' => 5
                        ],
                    ]
                ],
            ]]
        );

        // creating doughnut chart
        $stockChart = new StockChart();

        $stockChart->labels([
            'Medicine', 'Food', 'Hospital Goods', 'Injections', 'Merchandise', 'Lab Work', 'Surcharges', 'Theatre',
            'Vaccines', 'X-rays', 'Grooming Stock', 'General Services'
        ]);

        $colours = array(
            "#e61109", "#12B3DC", "#8AC007", "#ed660c", "#15e6bc", "#e6b909", "#021577", "#4acf08", "#0966d9",
            "#7c05f2", "#2f6e45", "#021668",
        );

        DB::table($name . '.' . 'sales')->truncate();

        $stockArray = array();

        $cType = Type::where('type', '=', 'I')->first();
        $sql = "select ttype, sum(amount) as amount, sum(dis_amount) as dis_amount, sum(tax_amount) as
            tax_amount, sum(cost) as cost, sum(qty) as qty from $name.curbatch where dbat_date >= '$start_date' and
            dbat_date <= '$end_date' and type_id = $cType->id group by ttype";
        $curbatch = DB::select($sql);
        foreach ($curbatch as $curbat) {
            if (
                $curbat->ttype == 'B' or $curbat->ttype == 'D' or $curbat->ttype == 'R' or $curbat->ttype == 'Y' or
                $curbat->ttype == 'Q' or $curbat->ttype == 'A' or $curbat->ttype == 'C' or $curbat->ttype == 'P' or
                $curbat->ttype == 'O' or $curbat->ttype == 'Z' or $curbat->ttype == 'K' or $curbat->ttype == 'G'
            )
                continue;

            if ($curbat->ttype == 'E')
                $curbat->ttype = 'M';

            $curbatType = Type::where('type', '=', $curbat->ttype)->first();
            $sales = Sales::where('type_id', '=', $curbatType->id)->first();
            if ($sales) {
                $sales->amount = $sales->amount + $curbat->amount;
                $sales->discount = $sales->discount + $curbat->dis_amount;
                $sales->cost = $sales->cost + $curbat->cost;
                $sales->vat = $sales->vat + $curbat->tax_amount;
                $sales->profit = $sales->profit + (($curbat->amount + $curbat->dis_amount) - $curbat->cost);
                $sales->last_sale = Carbon::now();
                $sales->qty = $sales->qty + $curbat->qty;
                if ($curbat->qty < 0)
                    $sales->no_sales = $sales->no_sales - 1;
                else
                    $sales->no_sales = $sales->no_sales + 1;
                $sales->mass = null;
                $sales->type_id = $curbatType->id;
                $sales->update();
            } else {
                $sales = new Sales();
                $sales->ref = '???';
                $sales->qty = $curbat->qty;
                $sales->amount = $curbat->amount;
                $sales->discount = $curbat->dis_amount;
                $sales->vat = $curbat->tax_amount;
                $sales->cost = $curbat->cost;
                $sales->profit = (($curbat->amount + $curbat->dis_amount) - $curbat->cost);
                $sales->last_sale = Carbon::now();
                if ($curbat->qty < 0)
                    $sales->no_sales = -1;
                else
                    $sales->no_sales = 1;
                $sales->mass = null;
                $sales->type_id = $curbatType->id;
                $sales->save();
            }
        }
        $iType = Type::where('type', '=', 'I')->first();
        $sql = "select ttype, sum(amount) as amount, sum(dis_amount) as dis_amount, sum(tax_amount) as
            tax_amount, sum(cost) as cost, sum(qty) as qty from $name.dompojb where dpojb_date >= '$start_date' and
            dpojb_date <= '$end_date' and type_id = $iType->id group by ttype";
        $dompojb = DB::select($sql);
        foreach ($dompojb as $dompoj) {
            if (
                $dompoj->ttype == 'B' or $dompoj->ttype == 'D' or $dompoj->ttype == 'R' or $dompoj->ttype == 'Y' or
                $dompoj->ttype == 'Q' or $dompoj->ttype == 'A' or $dompoj->ttype == 'C' or $dompoj->ttype == 'P' or
                $dompoj->ttype == 'O' or $dompoj->ttype == 'Z' or $dompoj->ttype == 'K' or $dompoj->ttype == 'G'
            )
                continue;

            if ($dompoj->ttype == 'E')
                $dompoj->ttype = 'M';

            $dompojType = Type::where('type', '=', $dompoj->ttype)->first();
            $sales = Sales::where('type_id', '=', $dompojType->id)->first();
            if ($sales) {
                $sales->amount = $sales->amount + $dompoj->amount;
                $sales->discount = $sales->discount + $dompoj->dis_amount;
                $sales->cost = $sales->cost + $dompoj->cost;
                $sales->vat = $sales->vat + $dompoj->tax_amount;
                $sales->profit = $sales->profit + (($dompoj->amount + $dompoj->dis_amount) - $dompoj->cost);
                $sales->last_sale = Carbon::now();
                $sales->qty = $sales->qty + $dompoj->qty;
                if ($dompoj->qty < 0)
                    $sales->no_sales = $sales->no_sales - 1;
                else
                    $sales->no_sales = $sales->no_sales + 1;
                $sales->mass = null;
                $sales->type_id = $dompojType->id;
                $sales->update();
            } else {
                $sales = new Sales();
                $sales->ref = '????';
                $sales->qty = $dompoj->qty;
                $sales->amount = $dompoj->amount;
                $sales->discount = $dompoj->dis_amount;
                $sales->vat = $dompoj->tax_amount;
                $sales->cost = $dompoj->cost;
                $sales->profit = (($dompoj->amount + $dompoj->dis_amount) - $dompoj->cost);
                $sales->last_sale = Carbon::now();
                if ($dompoj->qty < 0)
                    $sales->no_sales = -1;
                else
                    $sales->no_sales = 1;
                $sales->mass = null;
                $sales->type_id = $dompojType->id;
                $sales->save();
            }
        }
        $sales = Sales::where('id', '>', 0)->get();
        $labelCnt = count($stockChart->labels);
        $i = 0;
        foreach ($stockChart->labels as $label) {
            $found = 'N';
            foreach ($sales as $sale) {
                $type = Type::where('id', '=', $sale->type_id)->first();
                if ($type->description != $label)
                    continue;
                $stockArray[$i] = $sale->amount;
                $found = 'Y';
            }
            if ($found == 'Y')
                $i = $i + 1;
        }
        while ($i < $labelCnt) {
            $stockArray[$i] = null;
            $i = $i + 1;
        }
        $stockChart->dataset('Stock Movement', 'doughnut', [
            $stockArray[0], $stockArray[1], $stockArray[2], $stockArray[3], $stockArray[4], $stockArray[5], $stockArray[6],
            $stockArray[7], $stockArray[8], $stockArray[9], $stockArray[10], $stockArray[11]
        ])
            ->color($colours)
            ->backgroundcolor($colours)
            ->options([
                'fill' => 'false',
            ]);

        $stockChart->displayLegend('true')
            ->options([

                'legend' => [
                    'responsive' => 'true',
                    'display' => 'true',
                    'position' => 'right',
                    'fullWidth' => 'true',
                    'maxHeight' => '22',
                ],
            ]);

        // creating bar chart
        $saleChart = new SaleChart();

        if ($month == '1' or $month == '3' or $month == '5' or $month == '7' or $month == '8' or $month == '10' or $month == '12')
            $saleChart->labels([
                '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15',
                '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'
            ]);
        elseif ($month == '4' or $month == '6' or $month == '9' or $month == '11')
            $saleChart->labels([
                '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15',
                '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30'
            ]);
        elseif ($month == '2')
            if ($quotient > 0)
                $saleChart->labels([
                    '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15',
                    '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28'
                ]);
            else
                $saleChart->labels([
                    '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15',
                    '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29'
                ]);

        $labelsCnt = count($saleChart->labels);

        $dompojb = DB::select("select dpojb_date as ddate, sum(amount) from $name.dompojb where dpojb_date >=
            '$start_date' and dpojb_date <= '$end_date' and (ttype = 'F' or ttype = 'J' or ttype = 'K') GROUP BY dpojb_date");
        $curbatch = DB::select("select dbat_date as ddate, sum(amount) from $name.curbatch where dbat_date >=
            '$start_date' and dbat_date <= '$end_date' and (ttype = 'F' or ttype = 'J' or ttype = 'K')GROUP BY dbat_date");

        $records = array_merge($dompojb, $curbatch);

        $daysArray = array();
        $i = 0;
        foreach ($records as $rec) {
            $daysArray[$i] = $rec->sum;
            $i = $i + 1;
        }
        while ($i < $labelsCnt) {
            $daysArray[$i] = null;
            $i = $i + 1;
        }
        if ($month == '1' or $month == '3' or $month == '5' or $month == '7' or $month == '8' or $month == '10' or $month == '12')
            $saleChart->dataset('Daily Sales', 'bar', [
                $daysArray[0], $daysArray[1], $daysArray[2], $daysArray[3],
                $daysArray[4], $daysArray[5], $daysArray[6], $daysArray[7], $daysArray[8], $daysArray[9], $daysArray[10],
                $daysArray[11], $daysArray[12], $daysArray[13], $daysArray[14], $daysArray[15], $daysArray[16], $daysArray[17],
                $daysArray[18], $daysArray[19], $daysArray[20], $daysArray[21], $daysArray[22], $daysArray[23], $daysArray[24],
                $daysArray[25], $daysArray[26], $daysArray[27], $daysArray[28], $daysArray[29],  $daysArray[30]
            ])->options([
                'fill' => 'true',
                'borderColor' => '#4A5170',
                'backgroundColor' => '#1937bf',
            ]);
        elseif ($month == '4' or $month == '6' or $month == '9' or $month == '11')
            $saleChart->dataset('Daily Sales', 'bar', [
                $daysArray[0], $daysArray[1], $daysArray[2], $daysArray[3],
                $daysArray[4], $daysArray[5], $daysArray[6], $daysArray[7], $daysArray[8], $daysArray[9], $daysArray[10],
                $daysArray[11], $daysArray[12], $daysArray[13], $daysArray[14], $daysArray[15], $daysArray[16], $daysArray[17],
                $daysArray[18], $daysArray[19], $daysArray[20], $daysArray[21], $daysArray[22], $daysArray[23], $daysArray[24],
                $daysArray[25], $daysArray[26], $daysArray[27], $daysArray[28], $daysArray[29]
            ])->options([
                'fill' => 'true',
                'borderColor' => '#4A5170',
                'backgroundColor' => '#1937bf',
            ]);
        elseif ($month == '2')
            if ($quotient > 0) {
                $saleChart->dataset('Daily Sales', 'bar', [
                    $daysArray[0], $daysArray[1], $daysArray[2], $daysArray[3],
                    $daysArray[4], $daysArray[5], $daysArray[6], $daysArray[7], $daysArray[8], $daysArray[9], $daysArray[10],
                    $daysArray[11], $daysArray[12], $daysArray[13], $daysArray[14], $daysArray[15], $daysArray[16], $daysArray[17],
                    $daysArray[18], $daysArray[19], $daysArray[20], $daysArray[21], $daysArray[22], $daysArray[23], $daysArray[24],
                    $daysArray[25], $daysArray[26], $daysArray[27]
                ])->options([
                    'fill' => 'true',
                    'borderColor' => '#51C1C0',
                    'backgroundColor' => '#ffffff'
                ]);
            } else {
                $saleChart->dataset('Daily Sales', 'bar', [
                    $daysArray[0], $daysArray[1], $daysArray[2], $daysArray[3],
                    $daysArray[4], $daysArray[5], $daysArray[6], $daysArray[7], $daysArray[8], $daysArray[9], $daysArray[10],
                    $daysArray[11], $daysArray[12], $daysArray[13], $daysArray[14], $daysArray[15], $daysArray[16], $daysArray[17],
                    $daysArray[18], $daysArray[19], $daysArray[20], $daysArray[21], $daysArray[22], $daysArray[23], $daysArray[24],
                    $daysArray[25], $daysArray[26], $daysArray[27], $daysArray[28]
                ])->options([
                    'fill' => 'true',
                    'borderColor' => '#51C1C0',
                    'backgroundColor' => '#ffffff'
                ]);
            }
        return view('dashboard.index', compact('create_date', 'selected_date', 'consultationChart', 'stockChart', 'saleChart', 'start_date', 'end_date'));
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
