<?php

namespace Booktics\Models;

use Booktics\Abstracts\Model;

/**
 * Class Order_Model
 *
 * Handles database operations for orders in the Booktics system.
 *
 * @package Booktics\Models
 */
class Order_Model extends Model {
    protected $table = 'booktics_orders';
    protected $fillable = [
        'id',
        'order_no',
        'customer_id',
        'customer_note',
        'status',
        'payment_status',
        'price_breakdown',
        'tax_total',
        'coupon_code',
        'coupon_discount',
        'subtotal',
        'total',
        'currency',
        'payment_method',
        'payment_intent_id',
        'payment_transaction_id',
        'created_at',
        'updated_at',
        'custom_fields',
        'directorist_id',
    ];

    /**
     * Create a new order record
     *
     * @param array $data Order data to be created
     *
     * @return mixed The created order record
     */
    public function create( array $data ) {
        if ( empty( $data['order_no'] ) ) {
            $data['order_no'] = $this->generate_order_no();
        }

        $data['price_breakdown'] = wp_json_encode( $data['price_breakdown'] );

        return parent::create( $data );
    }


    /**
     * Generate a unique order number
     *
     * @return string
     */
    protected function generate_order_no() {
        $randomNum = time();

        return 'BKNG-' . $randomNum;
    }

    /**
     * Calculate total revenue for fully paid orders within a date range
     * Excludes canceled/cancelled orders
     *
     * @param string $start_date Start date (Y-m-d format)
     * @param string $end_date End date (Y-m-d format)
     * @param array $order_ids Optional array of order IDs to filter by
     *
     * @return float Total revenue
     */
    public function get_revenue_by_date_range( string $start_date, string $end_date, array $order_ids = array() ) {
        $query = $this->query()
            ->where( 'payment_status', '=', 'fully_paid' )
            ->where( 'status', '!=', 'canceled' )
            ->where( 'status', '!=', 'cancelled' )
            ->where( 'created_at', '>=', $start_date . ' 00:00:00' )
            ->where( 'created_at', '<=', $end_date . ' 23:59:59' );

        if ( ! empty( $order_ids ) ) {
            $query->where_in( 'id', $order_ids );
        }

        $sum = $query->sum( 'total' );

        // Additional safety check to ensure we always return a valid float
        if ( !is_numeric( $sum ) || !is_finite( $sum ) ) {
            return 0.0;
        }

        return (float) $sum;
    }

    /**
     * Calculate revenue for a specific date range with custom filters
     *
     * @param string $start_date Start date (Y-m-d format)
     * @param string $end_date End date (Y-m-d format)
     * @param callable|null $additional_conditions Callback to add additional conditions to the query
     *
     * @return float Total revenue
     */
    public function get_revenue_with_conditions( string $start_date, string $end_date, ?callable $additional_conditions = null ) {
        $query = $this->query()
            ->where( 'payment_status', '=', 'fully_paid' )
            ->where( 'status', '!=', 'canceled' )
            ->where( 'status', '!=', 'cancelled' )
            ->where( 'created_at', '>=', $start_date . ' 00:00:00' )
            ->where( 'created_at', '<=', $end_date . ' 23:59:59' );

        if ( $additional_conditions && is_callable( $additional_conditions ) ) {
            $additional_conditions( $query );
        }

        $sum = $query->sum( 'total' );

        // Additional safety check to ensure we always return a valid float
        if ( !is_numeric( $sum ) || !is_finite( $sum ) ) {
            return 0.0;
        }

        return (float) $sum;
    }
}