<?php
namespace orderflow;

class Incomplete_Orders_Tracker {
    private $table_name;

    public function __construct() {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'ads_incomplete_orders_tracker';
    }

    public function get_analytics($start_date, $end_date) {
        global $wpdb;

        // Get incomplete orders created in date range
        $created = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM $this->table_name 
            WHERE created_at BETWEEN %s AND %s
        ", $start_date . ' 00:00:00', $end_date . ' 23:59:59'));

        // Get recovered orders that were created in date range
        // Recovered orders are those where status_to is 'ads-recovered' (পরিবর্তিত)
        $recovered = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM $this->table_name 
            WHERE created_at BETWEEN %s AND %s
            AND status_to = 'ads-recovered' -- পরিবর্তন: status_to != 'ads-incomplete' থেকে status_to = 'ads-recovered'
        ", $start_date . ' 00:00:00', $end_date . ' 23:59:59'));

        // Get recovery amount for orders created in date range
        $recovery_amount = $wpdb->get_var($wpdb->prepare("
            SELECT SUM(order_total) 
            FROM $this->table_name 
            WHERE created_at BETWEEN %s AND %s
            AND status_to = 'ads-recovered' -- পরিবর্তন: status_to != 'ads-incomplete' থেকে status_to = 'ads-recovered'
        ", $start_date . ' 00:00:00', $end_date . ' 23:59:59'));

        // Get top recovery days for orders created in date range
        // We'll use recovered_at for the date, but only for orders that are actually recovered
        $top_days = $wpdb->get_results($wpdb->prepare("
            SELECT DATE(recovered_at) as recovery_date, 
                   COUNT(*) as recovered_carts,
                   SUM(order_total) as recovered_revenue
            FROM $this->table_name 
            WHERE created_at BETWEEN %s AND %s
            AND status_to = 'ads-recovered' -- পরিবর্তন: status_to != 'ads-incomplete' থেকে status_to = 'ads-recovered'
            AND recovered_at IS NOT NULL
            GROUP BY DATE(recovered_at)
            ORDER BY recovered_carts DESC, recovered_revenue DESC
            LIMIT 10
        ", $start_date . ' 00:00:00', $end_date . ' 23:59:59'));

        return [
            'created' => $created,
            'recovered' => $recovered,
            'recovery_rate' => $created > 0 ? round(($recovered / $created) * 100, 2) : 0,
            'recovery_amount' => $recovery_amount ?: 0,
            'top_days' => $top_days
        ];
    }
}