<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PriceSetup;
use App\Models\Helpers\General;
use Yajra\DataTables\Facades\DataTables;

class PriceSetupController extends Controller
{
    public function __construct()
    {
        return $this->middleware('auth');
    }

    public function index(){
        // dd('I work');
        $activeprice = PriceSetup::where('status', 'Active')->first();
        if (request()->ajax()) {
            $data = PriceSetup::all();
            return DataTables::of($data)->make(true);
        }
        return view('price_setup.price_history', compact('activeprice'));
    }
    
    public function new_price(){
       
        $price =PriceSetup::where('status', 'Active')->first();
        // dd(compact('price'));
        return view('price_setup.new_price',compact('price'));
    }
    
    public function change_price(Request $request){
        // dd($request->all());
        $request->validate([
            'current_price'=>'required|numeric',
            'new_price'=>'required|numeric',
            'description'=>'required|string',
        ]);

        $priceData = [
            'previous_price'=>$request->current_price,
            'current_price'=>$request->new_price,
            'description'=>$request->description,
            'status'=>'Active'
        ];

        try {
            //code...
            $pricecount = PriceSetup::all()->count(); //Check if there is a price in DB
            if($pricecount == 0){
                //No price exist create fresh one
                PriceSetup::create([
                    'previous_price'=>$request->current_price,
                    'current_price'=>$request->new_price,
                    'description'=>$request->description,
                    'status'=>'Active'
                ]);
            }else{
                $currentPrice = PriceSetup::where('status', 'Active')->first();

                if (!empty($currentPrice) && !empty($currentPrice->status)){
    
                    $currentPrice->status = 'Inactive';
                    $currentPrice->save();
                
                    PriceSetup::create($priceData);
                }else{
                    return back()->with('error', 'Sorry, no current price found');
                }
            }
            return redirect()->route('pricesetup.index')->with('success', 'Price has been changed successfully');
        } catch (\Throwable $th) {
            //throw $th;
            General::logError('TRYING TO CHANGE SERVICE PRICE, BUT FAILED ', $th->getMessage(), 'change_price method in PriceSetupController');
            return back()->with('error', 'Sorry, there was error while changing the current price');
        }
        
    }

}
