<?php
/**
 * Migration class for the 'payments' table.
 */

namespace RadiusTheme\RadiusBooking\Databases\Table;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}
use RadiusTheme\RadiusBooking\Core\Database\Schema\Blueprint;
use RadiusTheme\RadiusBooking\Abstracts\Migration;
use RadiusTheme\RadiusBooking\Core\Database\Schema\Schema;

/**
 * Class PaymentsTable
 *
 * @package RadiusTheme\RadiusBooking\Databases\Table
 * Migration for creating the 'payments' table.
 */
class PaymentsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up(): void {
		Schema::create(
			$this->tablePrefix . 'payments',
			function ( Blueprint $table ) {
				$table->id();
				$table->unsignedInteger( 'booking_id' );
				$table->unsignedInteger( 'customer_id' )->nullable();
				$table->string( 'transaction_id' )->nullable();
				$table->string( 'payment_method' )->default( 'offline' );
				$table->double( 'amount' )->default( 0.00 );
				$table->double( 'total_amount' )->default( 0.00 );
				$table->double( 'due_amount' )->default( 0.00 );
				$table->enum( 'status', array( 'pending', 'completed', 'paid', 'failed', 'refunded', 'partial_payment' ) )->default( 'pending' );
				$table->dateTime( 'booking_date_time' );
				$table->unsignedInteger( 'parent_id' )->nullable();
				$table->string( 'booking_type' )->default( 'service_booking' );
				$table->unsignedInteger( 'invoice_id' )->nullable();
				$table->timestamp( 'paid_at' )->nullable();
				$table->timestamp( 'cancelled_at' )->nullable();
				$table->unsignedInteger( 'coupon_id' )->nullable();
				$table->string( 'coupon_code' )->nullable();
				$table->double( 'discount_amount' )->default( 0 );
				$table->double( 'tax_rate' )->default( 0 );
				$table->double( 'tax_amount' )->default( 0 );
				// Snapshot of the commission setting at the moment the payment
				// became paid/partial. Used by payout calculations so a later
				// rate change doesn't retroactively re-commission past earnings.
				$table->double( 'commission_rate' )->nullable();
				$table->string( 'commission_type', 20 )->nullable();
				$table->timestamps();
			}
		);
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down(): void {
		Schema::drop( $this->tablePrefix . 'payments' );
	}
}
