<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Payment;

class Form extends Model
{
    use HasFactory;
    protected $table = 'forms';
    protected $fillable = ['form_name','form_table_name','vtiger_product_id'];

    public function formPrices()
    {
        return $this->hasOne(FormPrice::class);
    }

    public static function getFormsWithPrices()
    {
        return self::with('formPrices')->get();
    }

    public static function getFormDataByFormTableName($form_table_name)
    {
        $result =  self::select('id as form_id','form_name','form_table_name','vtiger_product_id')->where('form_table_name', $form_table_name)->where('status', 'enabled')->get();

        if ($result !== null) {
            $response = $result->toArray();
        }else{
            $response = [];
        }
        
        return $response;
       
    }

    /**
     * Authour :Gurupriya Solanki
     * Update Date : 24 April 2024
     * This function is used to genreate unique order id  for payment
     * Starting 3 chartacter of  prefix, last two digits of current year, and random 5-digit number
     */
    public static function getOrderIdForPayment($prefix,$form_data_id,$form_type){

        do{
            // Get the last two digits of the current year
            $current_year = date("y");
            
            // Generate a random 5-digit number
            $random_digits = str_pad(mt_rand(0, 99999), 5, '0', STR_PAD_LEFT);
            
            // Starting 3 chartacter of  prefix, last two digits of current year, and random 5-digit number
            $unique_order_id = $prefix . $current_year . $random_digits;

            // Check if the generated reference ID already exists in the database
            $count = Payment::where("reference_id", $unique_order_id)->count();
        }while($count > 0);


        return $unique_order_id;
    }
    
}
