<?php

namespace EasyInvoice\Services;

/**
 * Quote Expiration Service
 * 
 * Handles background process for checking and updating expired quotes
 * 
 * @since 2.0.0
 */
class QuoteExpirationService {

    /**
     * Initialize the service
     * 
     * @since 2.0.0
     */
    public static function init() {
        add_action( 'easy_invoice_quote_expiration_check', [ __CLASS__, 'check_expired_quotes' ] );
        add_action( 'init', [ __CLASS__, 'schedule_expiration_check' ] );
    }

    /**
     * Schedule the quote expiration check
     * 
     * @since 2.0.0
     */
    public static function schedule_expiration_check() {
        if ( ! wp_next_scheduled( 'easy_invoice_quote_expiration_check' ) ) {
            wp_schedule_event( time(), 'daily', 'easy_invoice_quote_expiration_check' );
        }
    }

    /**
     * Check for expired quotes and update their status
     * 
     * @since 2.0.0
     */
    public static function check_expired_quotes() {
        global $wpdb;

        // Get current date in Y-m-d format
        $current_date = current_time( 'Y-m-d' );

        // Find quotes that are past their due date and not already expired
        $expired_quotes = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT p.ID, p.post_title 
                FROM {$wpdb->posts} p 
                INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id 
                WHERE p.post_type = 'easy_quote' 
                AND p.post_status IN ('publish', 'draft') 
                AND pm.meta_key = '_easy_invoice_quote_expiry_date' 
                AND pm.meta_value < %s 
                AND p.ID NOT IN (
                    SELECT post_id 
                    FROM {$wpdb->postmeta} 
                    WHERE meta_key = '_easy_invoice_quote_status' 
                    AND meta_value = 'expired'
                )",
                $current_date
            )
        );

        if ( empty( $expired_quotes ) ) {
            return;
        }

        $updated_count = 0;

        foreach ( $expired_quotes as $quote ) {
            // Update the quote status to expired
            update_post_meta( $quote->ID, '_easy_invoice_quote_status', 'expired' );           
            
            $updated_count++;
        }
    }

    /**
     * Manually trigger quote expiration check
     * 
     * @since 2.0.0
     */
    public static function manual_check_expired_quotes() {
        self::check_expired_quotes();
    }

    /**
     * Clear the scheduled event on plugin deactivation
     * 
     * @since 2.0.0
     */
    public static function clear_schedule() {
        wp_clear_scheduled_hook( 'easy_invoice_quote_expiration_check' );
    }
} 