<?php
/**
 * Deposit (acompte) handler
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

/**
 * Deposit handler class
 */
class WAHRB_Deposit_Handler {

    /**
     * Calculate deposit amount
     *
     * @param float $total Total amount
     * @param array $settings Payment settings
     * @return float
     */
    public static function calculate(float $total, array $settings): float {
        if (empty($settings['deposit_enabled'])) {
            return 0;
        }

        $type = $settings['deposit_type'] ?? 'percent';
        $value = floatval($settings['deposit_value'] ?? 30);

        if ($type === 'percent') {
            return round($total * ($value / 100), 2);
        }

        return min($value, $total);
    }

    /**
     * Process deposit refund
     *
     * @param int $booking_id Booking ID
     * @param float $amount Refund amount
     * @return bool
     */
    public static function refund(int $booking_id, float $amount): bool {
        $booking = new WAHRB_Booking($booking_id);
        if (!$booking->exists()) {
            return false;
        }

        $schedule = $booking->get_payment_schedule();
        if (!$schedule || $schedule['deposit_status'] !== 'paid') {
            return false;
        }

        $order_id = $schedule['deposit_order_id'];
        if (!$order_id) {
            return false;
        }

        $order = wc_get_order($order_id);
        if (!$order) {
            return false;
        }

        // Create refund
        $refund = wc_create_refund([
            'amount' => $amount,
            'reason' => __('Deposit refund', 'wahra-rentals-bookings'),
            'order_id' => $order_id,
            'refund_payment' => true,
        ]);

        if (is_wp_error($refund)) {
            return false;
        }

        // Update status
        global $wpdb;
        $db = WAHRB_Database::instance();

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $wpdb->update(
            $db->table('payment_schedule'),
            ['deposit_status' => 'refunded'],
            ['booking_id' => $booking_id]
        );

        return true;
    }
}
