<?php
namespace orderflow\Admin;

if (!defined('ABSPATH')) {
    exit;
}

use orderflow\Incomplete_Orders_Tracker;

class Incomplete_Orders_Dashboard {
    private $tracker;

    public function __construct() {
        $this->tracker = new Incomplete_Orders_Tracker();
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('wp_ajax_ads_get_analytics_data', [$this, 'get_analytics_data']);
    }

    public function enqueue_scripts($hook) {
        wp_enqueue_style('ads-admin-css', ADS_PLUGIN_URL . 'assets/css/admin.css', [], ADS_VERSION);
        wp_enqueue_script('chartjs', 'https://cdn.jsdelivr.net/npm/chart.js', [], '3.9.1', true);
        wp_enqueue_script('ads-analytics-js', ADS_PLUGIN_URL . 'assets/js/analytics.js', ['jquery', 'chartjs'], ADS_VERSION, true);
        wp_localize_script('ads-analytics-js', 'ads_analytics', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('ads_analytics_nonce'),
            'currency_symbol' => get_woocommerce_currency_symbol(),
            'date_format' => get_option('date_format'),
        ]);

        if ($hook !== 'toplevel_page_orderflow') {
            return;
        }

        // Tailwind CSS
        wp_enqueue_style('tailwindcss', 'https://cdn.tailwindcss.com');
        // Google Fonts
        wp_enqueue_style('google-fonts-inter', 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
        // Lucide Icons
        wp_enqueue_script('lucide-icons', 'https://unpkg.com/lucide@latest/dist/umd/lucide.min.js', array(), null, true);
        wp_add_inline_script('lucide-icons', 'lucide.createIcons();');
    }

    public function render_dashboard() {
        ?>

        <?php
    }
    public function get_analytics_data() {
        check_ajax_referer('ads_analytics_nonce', 'nonce');
        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Permission denied');
        }

        $from = isset($_POST['from']) ? sanitize_text_field($_POST['from']) : date('Y-m-d', strtotime('-30 days'));
        $to = isset($_POST['to']) ? sanitize_text_field($_POST['to']) : date('Y-m-d');

        // Get analytics data from tracker
        $analytics = $this->tracker->get_analytics($from, $to);

        // Get incomplete orders by day
        $incomplete_by_day = $this->get_incomplete_orders_by_day($from, $to);

        // Get orders by status
        $orders_by_status = $this->get_orders_by_status($from, $to);

        // Get top recovery days
        $top_recovery_days = $this->get_top_recovery_days($from, $to);

        // Calculate total recovery orders (sum of all non-incomplete statuses)
        $total_recovery_orders = 0;
        foreach ($orders_by_status['data'] as $key => $count) {
            $status = $orders_by_status['labels'][$key];
            if ($status !== 'Incomplete') {
                $total_recovery_orders += $count;
            }
        }

        // Get incomplete count
        $incomplete_count = $orders_by_status['incomplete'] ?? 0;

        wp_send_json_success([
            'total_incomplete' => $incomplete_count,
            'total_recovery_orders' => $total_recovery_orders,
            'recovery_rate' => $analytics['recovery_rate'],
            'recovery_amount' => $analytics['recovery_amount'],
            'incomplete_by_day' => $incomplete_by_day,
            'orders_by_status' => $orders_by_status,
            'top_recovery_days' => $top_recovery_days
        ]);
    }

    private function get_incomplete_orders_by_day($from, $to) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_incomplete_orders_tracker';
        $results = $wpdb->get_results($wpdb->prepare("
            SELECT DATE(created_at) as date, COUNT(*) as count
            FROM $table_name
            WHERE created_at BETWEEN %s AND %s
            AND status_to = 'ads-incomplete'
            GROUP BY DATE(created_at)
            ORDER BY date ASC
        ", $from . ' 00:00:00', $to . ' 23:59:59'));

        $data = [
            'labels' => [],
            'data' => []
        ];

        // Fill missing dates
        $period = new \DatePeriod(
            new \DateTime($from),
            new \DateInterval('P1D'),
            new \DateTime($to . ' +1 day')
        );

        $counts = [];
        foreach ($results as $row) {
            $counts[$row->date] = $row->count;
        }

        foreach ($period as $day) {
            $date = $day->format('Y-m-d');
            $data['labels'][] = $date;
            $data['data'][] = $counts[$date] ?? 0;
        }

        return $data;
    }

    private function get_orders_by_status($from, $to) {
        global $wpdb;

        // নতুন স্ট্যাটাস ads-recovered যোগ করা হয়েছে
        $statuses = [
            'ads-incomplete' => 'incomplete',
            'ads-recovered' => 'recovered', // পরিবর্তন: ads-purchase থেকে ads-recovered
            'processing' => 'pending',
            'completed' => 'completed',
            'cancelled' => 'cancelled',
            'failed' => 'failed',
            'refunded' => 'refunded'
        ];

        $data = [
            'labels' => [],
            'data' => [],
            'backgroundColors' => [],
            'incomplete' => 0
        ];

        // নতুন স্ট্যাটাসের জন্য রঙ যোগ করা হয়েছে
        $colors = [
            'ads-incomplete' => '#FF6384',
            'ads-recovered' => '#36A2EB', // পরিবর্তন: ads-purchase থেকে ads-recovered
            'processing' => '#36A2EB',
            'completed' => '#4BC0C0',
            'cancelled' => '#FFCE56',
            'failed' => '#FF6384',
            'refunded' => '#9966FF'
        ];

        $tracker_table = $wpdb->prefix . 'ads_incomplete_orders_tracker';

        foreach ($statuses as $status => $label) {
            if (in_array($status, ['ads-incomplete', 'ads-recovered'])) { // পরিবর্তন: ads-purchase থেকে ads-recovered
                // Get counts from tracker table for custom statuses
                $count = $wpdb->get_var($wpdb->prepare("
                    SELECT COUNT(DISTINCT order_id) 
                    FROM $tracker_table 
                    WHERE status_to = %s
                    AND created_at BETWEEN %s AND %s
                ", $status, $from . ' 00:00:00', $to . ' 23:59:59'));
            } else {
                // Use WooCommerce function for standard statuses
                $wc_status = 'wc-' . $status;
                $count = wc_orders_count($wc_status);
            }

            // Only include incomplete and recovery statuses in the chart
            if ($status === 'ads-incomplete' || $status === 'ads-recovered') { // পরিবর্তন: ads-purchase থেকে ads-recovered
                $data['labels'][] = ucfirst($label);
                $data['data'][] = $count;
                $data['backgroundColors'][] = $colors[$status];
            }

            if ($status === 'ads-incomplete') {
                $data['incomplete'] = $count;
            }
        }

        return $data;
    }

    private function get_top_recovery_days($from, $to) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_incomplete_orders_tracker';

        // পরিবর্তন: শুধুমাত্র ads-recovered স্ট্যাটাসের জন্য ডেটা নেওয়া হচ্ছে
        $results = $wpdb->get_results($wpdb->prepare("
            SELECT DATE(recovered_at) as recovery_date, 
                   COUNT(*) as recovered_carts,
                   SUM(order_total) as recovered_revenue
            FROM $table_name 
            WHERE recovered_at BETWEEN %s AND %s
            AND status_to = 'ads-recovered' -- পরিবর্তন: status_to != 'ads-incomplete' থেকে status_to = 'ads-recovered'
            GROUP BY DATE(recovered_at)
            ORDER BY recovered_carts DESC, recovered_revenue DESC
            LIMIT 10
        ", $from . ' 00:00:00', $to . ' 23:59:59'));

        return $results;
    }
}