<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\CRMLog;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CRMLogController extends Controller
{
    public function changeCrmStatus(Request $request)
    {
        // if($request->crm_status_current == $request->crm_status_select){
        //     Toastr::error('Please select different status', 'Error');
        //     return redirect()->back();
        // }
        DB::beginTransaction();
        try{
            $crmLog = new CRMLog();
            $crmLog->client_id = $request->client_id;
            $crmLog->user_id = auth()->user()->id;
            $crmLog->previous_crm_status = $request->crm_status_current;
            $crmLog->new_crm_status = $request->crm_status_select;
            $crmLog->description = $request->description;
            if($request->crm_check_date){
                $crmLog->crm_check_date = $request->crm_check_date;
            }else{
                $crmLog->crm_check_date = null;
            }
            $crmLog->save();

            $client = Client::find($request->client_id);
            $client->crm_status = $request->crm_status_select;
            if($request->crm_check_date){

                $client->crm_check_date = $request->crm_check_date;
            }else{
                $client->crm_check_date = null;

            }
            $client->save();

            DB::commit();

           Toastr::success('Transfer successful', 'Success');
            return redirect()->back();

        }catch (\Exception $e){
            Toastr::error('Something went wrong', 'Error');
            return redirect()->back();
        }


    }

    public function crmChangeHistory($id){

        $start = Carbon::now()->startOfMonth()->format('Y-m-d 00:00:00');
        $end = Carbon::now()->endOfMonth()->format('Y-m-d 23:59:59');
        $data = [
            'logs' => CRMLog::with('changeBy')->where('client_id', $id)->get(),
        ];
        return view('crm.client.change_log', $data);


    }


}
