<?php

namespace App\Http\Controllers\Mitra;

use App\Http\Controllers\Controller;
use App\Models\Cultivation;
use App\Models\FishType;
use App\Models\HarvestFish;
use App\Models\Pond;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Yajra\DataTables\Facades\DataTables;

class CultivationController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // automated update status pond
        $today = Carbon::today();
        $ponds = Pond::where('user_id', Auth::user()->id)->get();
        foreach ($ponds as $pond) {
            $sow_date = Carbon::parse($pond->sow_date);
            $diffInDays = $today->diffInDays($sow_date);
            $diffInDays += 1;
            $max_day = $pond->cultivations->max('day');
            if ($diffInDays >= $max_day) {
                $pond->status = Pond::HARVEST;
                $pond->save();
            }
        }

        if ($request->ajax()) {
            // query get user data
            $query = Pond::where('user_id', Auth::user()->id)->get();

            // setup datatable
            return DataTables::of($query)
                ->addColumn('checkbox', function ($item) {
                    $checkbox = '<input  class="form-check-input id-check" type="checkbox" name="id[]" value="' . $item->id . '">';
                    return $checkbox;
                })
                ->addColumn('name', function ($item) {
                    return $item->name;
                })
                ->addColumn('sow_date', function ($item) {
                    return $item->date_sow;
                })
                ->addColumn('seed_amount', function ($item) {
                    return $item->seed_amount;
                })
                ->addColumn('volume_pond', function ($item) {
                    return $item->volume_pond;
                })
                ->addColumn('status', function ($item) {
                    $status = '';
                    if ($item->status == Pond::PROCESS) {
                        $status = '<span class="badge badge-info">Proses</span>';
                    } else if ($item->status == Pond::HARVEST) {
                        $status = '<span class="badge badge-light-warning">Panen</span>';
                    } else {
                        $status = '<span class="badge badge-light-danger">Nonaktif</span>';
                    }
                    return $status;
                })
                ->addColumn('actions', function ($item) {
                    $button = ' <a href="' . route('cultivation.show', $item->id) . '"
                                class="btn btn-light btn-active-light-primary btn-sm">Show</a> ';
                    return $button;
                })
                ->rawColumns(['checkbox', 'name', 'sow_date', 'seed_amount', 'volume_pond', 'status', 'actions'])
                ->make(true);
        }
        return view('mitra.cultivation.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $fish_type = FishType::all();
        return view('mitra.cultivation.create', compact('fish_type'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            // set data
            $fish_id = $request->fish_type;
            $seed_amount = $request->seed_amount;
            $seed_weight = $request->seed_weight;
            $pond_volume = $request->pond_volume;
            $total_fish_count = $request->total_fish_count;
            $survival_rate = HarvestFish::where('fish_type_id', $fish_id)->avg('survival_rate');
            $survival_rate = round($survival_rate, 1);
            $average_weight = 1000 / $total_fish_count;
            $average_weight = round($average_weight, 1);

            // get data prediction from API
            $url = config('app.api_python_url') . "/implements/prediction";
            $response = Http::get($url, [
                'fish_id' => $fish_id,
                'seed_amount' => $seed_amount,
                'seed_weight' => $seed_weight,
                'pond_volume' => $pond_volume,
                'total_fish_count' => $total_fish_count,
                'survival_rate' => $survival_rate
            ]);

            // check response successfull
            if ($response->successful()) {
                $data = $response->json();
                $simulation_table = $data['simulation_table'];
                $prediction = $data['predict'];
                $total_feed_spent = $data['total_feed_spent'];
            } else {
                // if request failed
                return back()->with('toast_error', "Terdapat Error pada API Python");
            }

            // new pond
            $pond                       = new Pond();
            $pond->user_id              = Auth::user()->id;
            $pond->fish_id              = $request->fish_type;
            $pond->name                 = $this->generateName($fish_id, Auth::user()->id);
            $pond->sow_date             = $request->sow_date;
            $pond->seed_amount          = $seed_amount;
            $pond->seed_weight          = $seed_weight;
            $pond->survival_rate        = $survival_rate;
            $pond->volume_pond          = $pond_volume;
            $pond->average_weight       = $average_weight;
            $pond->total_feed_spent     = $total_feed_spent;
            $pond->prediction           = $prediction;
            $pond->status               = Pond::PROCESS;
            $pond->save();

            // new cultivation
            foreach ($simulation_table as $value) {
                $cultivation = new Cultivation();
                $cultivation->pond_id = $pond->id;
                $cultivation->day = $value['day'];
                $cultivation->weight = $value['weight'];
                $cultivation->feed_spent = $value['feed_spent'];
                $cultivation->total_feed_spent = $value['total_feed_spent'];
                $cultivation->total_fish_weight = $value['total_weight'];
                $cultivation->save();
            }
            DB::commit();
            return redirect()->route('cultivation.index')->with('success', 'Berhasil menambahkan budidaya baru');
        } catch (\Throwable $th) {
            DB::rollback();
            return back()->with('toast_error', $th->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $pond = Pond::find($id);
        $today = Carbon::today();
        $today_date = Carbon::today()->locale('id')->isoFormat('D MMMM Y');
        $sow_date = Carbon::parse($pond->sow_date);
        $diffInDays = $today->diffInDays($sow_date);
        $diffInDays += 1;
        if($pond->status == Pond::PROCESS){
            $cultivation = Cultivation::where([['pond_id', $pond->id], ['day', $diffInDays]])->first();
        } else {
            $cultivation = Cultivation::where([['pond_id', $pond->id]])->latest()->first();
        }
        return view('mitra.cultivation.show', compact('pond', 'cultivation', 'today_date'));
    }

    /**
     * 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)
    {
        //
    }

    public function generateName($fish_id, $user_id)
    {
        $pond_count = Pond::where([['user_id', $user_id], ['fish_id', $fish_id]])->count();
        $pond_count += 1;
        $fish_name = FishType::find($fish_id)->name;
        $pond_name = "Kolam " . $fish_name . " " . $pond_count;
        return $pond_name;
    }

    public function getChartSimulation(Request $request)
    {
        $pond = Pond::find($request->pond_id);
        $data_weight = [];
        $data_feed = [];
        foreach($pond->cultivations as $data){
            $data_weight[] = [
                "x" => $data->day,
                "y" => $data->weight
            ];

            $data_feed[] = [
                "x" => $data->day,
                "y" => $data->feed_spent
            ];
        }
        return response()->json(['data_weight'=>$data_weight, 'data_feed'=>$data_feed]);
    }
}
