# Ruby Calculator - Interactive calculator built with Ruby on Rails
# Author: RSK World (Molla Samser, Founder | Rima Khatun, Designer & Tester)
# Contact: help@rskworld.in | +91 93305 39277
# Website: https://rskworld.in
# Year: 2026
# Description: Build a fully functional calculator using Ruby on Rails with modern UI

class FavoritesController < ApplicationController
  def index
    @favorites = FavoriteCalculation.recent
    @categories = FavoriteCalculation::CATEGORIES
  end
  
  def create
    @favorite = FavoriteCalculation.new(favorite_params)
    
    if @favorite.save
      respond_to do |format|
        format.html { redirect_to favorites_path, notice: "Favorite calculation saved!" }
        format.json { render json: { success: true, favorite: @favorite } }
      end
    else
      respond_to do |format|
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: { errors: @favorite.errors }, status: :unprocessable_entity }
      end
    end
  end
  
  def show
    @favorite = FavoriteCalculation.find(params[:id])
  end
  
  def update
    @favorite = FavoriteCalculation.find(params[:id])
    
    if @favorite.update(favorite_params)
      respond_to do |format|
        format.html { redirect_to @favorite, notice: "Favorite updated!" }
        format.json { render json: { success: true, favorite: @favorite } }
      end
    else
      respond_to do |format|
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: { errors: @favorite.errors }, status: :unprocessable_entity }
      end
    end
  end
  
  def destroy
    @favorite = FavoriteCalculation.find(params[:id])
    @favorite.destroy
    
    respond_to do |format|
      format.html { redirect_to favorites_path, notice: "Favorite deleted!" }
      format.json { render json: { success: true } }
    end
  end
  
  def use_favorite
    @favorite = FavoriteCalculation.find(params[:id])
    
    # Execute the calculation and save to history
    begin
      result = eval(@favorite.expression.gsub(/[^0-9+\-*/().\s]/, ''))
      
      CalculationHistory.create!(
        expression: @favorite.expression,
        result: result,
        operation: 'favorite_calculation'
      )
      
      respond_to do |format|
        format.html { redirect_to root_path, notice: "Calculation executed: #{result}" }
        format.json { render json: { result: result, expression: @favorite.expression } }
      end
    rescue => e
      respond_to do |format|
        format.html { redirect_to root_path, alert: "Error executing calculation" }
        format.json { render json: { error: e.message }, status: :unprocessable_entity }
      end
    end
  end
  
  private
  
  def favorite_params
    params.require(:favorite_calculation).permit(:name, :expression, :result, :category, :description)
  end
end
