<?php
/**
 * Payment Model
 */
namespace RadiusTheme\RadiusBooking\Models;

use RadiusTheme\RadiusBooking\Abstracts\BaseModel;
use RadiusTheme\RadiusBooking\Helpers\SettingsHelper;
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
/**
 * Class Payment
 *
 * @package RadiusTheme\RadiusBooking\Models
 *
 * @property int $id
 * @property string $name
 */
class Payment extends BaseModel {

	/**
	 * The database table associated with the model.
	 *
	 * @var string
	 */
	protected string $table = 'radius_booking_payments';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected array $fillable = array(
		'booking_id',
		'customer_id',
		'transaction_id',
		'payment_method',
		'amount',
		'total_amount',
		'due_amount',
		'status',
		'booking_date_time',
		'parent_id',
		'booking_type',
		'invoice_id',
		'paid_at',
		'cancelled_at',
		'coupon_id',
		'coupon_code',
		'discount_amount',
		'tax_rate',
		'tax_amount',
		'commission_rate',
		'commission_type',
	);

	/**
	 * Defines a relationship where the current model belongs to a CustomerBooking model.
	 */
	public function booking() {
		return $this->belongsTo( CustomerBooking::class, 'booking_id', 'id' );
	}

	/**
	 * Defines a relationship indicating that the current model belongs to a customer.
	 */
	public function customer() {
		return $this->belongsTo( User::class, 'customer_id', 'id' );
	}

	/**
	 * Retrieves the 'id' attribute of the current model.
	 *
	 * @return mixed The value of the 'id' attribute or null if not set.
	 */
	public function get_id() {
		return $this->attributes['id'] ?? null;
	}

	/**
	 * Calculates the total revenue by summing up the amounts of records
	 * with a status of 'paid' or 'partial_payment'.
	 *
	 * @return float The total revenue calculated from the specified records.
	 */
	public static function totalRevenue() {
		return static::whereIN( 'status', array( 'paid', 'partial_payment' ) )->sum( 'total_amount' );
	}

	/**
	 * Snapshot the current commission setting onto the payment row when it
	 * becomes paid/partial. The snapshot freezes per payment, so later changes
	 * to the global commission rate don't retroactively re-commission earnings
	 * already recorded.
	 *
	 * Skips if a snapshot already exists (commission_type !== null) so a
	 * status flip (e.g. paid → pending → paid) doesn't overwrite the original.
	 *
	 * @return void
	 */
	protected function onSaving(): void {
		$status = $this->attributes['status'] ?? null;
		if ( ! in_array( $status, array( 'paid', 'partial_payment' ), true ) ) {
			return;
		}
		if ( ! empty( $this->attributes['commission_type'] ) ) {
			return;
		}
		$settings = SettingsHelper::get_setting( 'payout' );
		if ( ! is_array( $settings ) || empty( $settings['enabled'] ) ) {
			return;
		}
		$this->attributes['commission_rate'] = (float) ( $settings['commissionRate'] ?? 0 );
		$this->attributes['commission_type'] = $settings['commissionType'] ?? 'percentage';
	}
}
