<?php 
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
echo '<div class="bwdcv-subscrive-info">';
    echo '<h1>' . esc_html__('Subscriber Information', 'cv-builder') . '</h1>';
    $args = [
        'post_type' => 'product',
        'posts_per_page' => -1,
        'post_status' => 'publish',
    ];
    $products = get_posts($args);
    echo '<div class="bwdcv-subscrive-info-wrap">';
    ?>
    <div class="bwdcv-subscrive-info-grid">
        <div class="bwdcv-subscrive-info-grid-item">
            <select  id="productName" onchange="filterTable()">
                <option value="all"><?php esc_html_e('Product Name', 'cv-builder'); ?></option>';
                <?php
                foreach ($products as $product) {
                    $product_id = $product->ID;
                    $cv_download = get_post_meta($product_id, '_subscription_per_download', true);
                    $subscription_billing_period = get_post_meta($product_id, '_subscription_billing_period', true);
                    if ($cv_download || $subscription_billing_period) {
                        $product_title = get_the_title($product_id);
                        echo '<option value="' . esc_attr($product_title) . '">' . esc_html($product_title) . '</option>';
                    }
                }
                ?>
            </select>
        </div>
        <div class="bwdcv-subscrive-info-grid-item">
            <select id="userName" onchange="filterTable()">
                <option value="all"><?php esc_html_e('Username', 'cv-builder'); ?></option>
                <?php
                $seen_users = [];
                foreach ($products as $product) {
                    $product_id = $product->ID;
                    $cv_download = get_post_meta($product_id, '_subscription_per_download', true);
                    $subscription_billing_period = get_post_meta($product_id, '_subscription_billing_period', true);
                    if ($cv_download || $subscription_billing_period) {
                        $orders = wc_get_orders([
                            'limit' => -1,
                            'status' => ['completed', 'processing'],
                        ]);
                        foreach ($orders as $order) {
                            if ($order instanceof WC_Order) {
                                $user_id = $order->get_customer_id();
                                $user = get_user_by('id', $user_id);
                                if ($user && in_array('cv_editor', $user->roles)) {
                                    $username = $user->user_login;
                                    if (!in_array($username, $seen_users)) {
                                        echo '<option value="' . esc_attr($username) . '">' . esc_html($username) . '</option>';
                                        $seen_users[] = $username;
                                    }
                                }
                            }
                        }
                    }
                }
                ?>
            </select>
        </div>
        <div class="bwdcv-subscrive-info-grid-item">
            <select id="planNames" onchange="filterTable()">
                <option value="all"><?php esc_html_e('Plan Name', 'cv-builder'); ?></option>
                <?php
                $query = new WP_Query($args);
                $plan_names = array();
                while ($query->have_posts()) {
                    $query->the_post();
                    $product_id = get_the_ID();
                    $plan_name = get_post_meta($product_id, '_subscription_plan_name', true);
                    if ($plan_name && !in_array($plan_name, $plan_names)) {
                        $plan_names[] = $plan_name;
                    }
                }
                wp_reset_postdata();
                foreach ($plan_names as $plan_name) {
                    echo '<option value="' . esc_attr($plan_name) . '">' . esc_html($plan_name) . '</option>';
                }
                ?>
            </select>
        </div>
        <div class="bwdcv-subscrive-info-grid-item">
            <select class="bwdcv-nice-select" id="billingPeriod" onchange="filterTable()">
                <option value="all"><?php esc_html_e('Billing Period', 'cv-builder'); ?></option>
                <option value="1"><?php esc_html_e('1 Day', 'cv-builder'); ?></option>
                <option value="30"><?php esc_html_e('30 Days', 'cv-builder'); ?></option>
                <option value="90"><?php esc_html_e('90 Days', 'cv-builder'); ?></option>
                <option value="183"><?php esc_html_e('183 Days', 'cv-builder'); ?></option>
                <option value="365"><?php esc_html_e('365 Days', 'cv-builder'); ?></option>
            </select>
        </div>
        <div class="bwdcv-subscrive-info-grid-item">
            <select class="bwdcv-nice-select" id="yearFilter" onchange="filterTable()">
                <option value="all"><?php esc_html_e('Year', 'cv-builder'); ?></option>
                <?php
                $activation_date = get_option('dynamic_year_dropdown_activation_date');
                $activation_year = date('Y', strtotime($activation_date));
                $current_year = date('Y');
                for ($year = $activation_year; $year <= $current_year; $year++) {
                    echo '<option value="' . $year . '">' . $year . '</option>';
                }
                ?>
            </select>
        </div>
        <div class="bwdcv-subscrive-info-grid-item">
            <select class="bwdcv-nice-select" id="monthFilter" onchange="filterTable()">
                <option value="all"><?php esc_html_e('Month', 'cv-builder'); ?></option>
                <option value="01"><?php esc_html_e('January', 'cv-builder'); ?></option>
                <option value="02"><?php esc_html_e('February', 'cv-builder'); ?></option>
                <option value="03"><?php esc_html_e('March', 'cv-builder'); ?></option>
                <option value="04"><?php esc_html_e('April', 'cv-builder'); ?></option>
                <option value="05"><?php esc_html_e('May', 'cv-builder'); ?></option>
                <option value="06"><?php esc_html_e('June', 'cv-builder'); ?></option>
                <option value="07"><?php esc_html_e('July', 'cv-builder'); ?></option>
                <option value="08"><?php esc_html_e('August', 'cv-builder'); ?></option>
                <option value="09"><?php esc_html_e('September', 'cv-builder'); ?></option>
                <option value="10"><?php esc_html_e('October', 'cv-builder'); ?></option>
                <option value="11"><?php esc_html_e('November', 'cv-builder'); ?></option>
                <option value="12"><?php esc_html_e('December', 'cv-builder'); ?></option>
            </select>
        </div>
        <div class="bwdcv-subscrive-info-grid-item">
            <select class="bwdcv-nice-select" id="dateFilter" onchange="filterTable()">
                <option value="all"><?php esc_html_e('Date', 'cv-builder'); ?></option>
                <?php
                for ($i = 1; $i <= 31; $i++) {
                    $value = sprintf("%02d", $i);
                    echo "<option value=\"$value\">$i</option>";
                }
                ?>
            </select>
        </div>
        <div class="bwdcv-subscrive-info-grid-item">
            <select class="bwdcv-nice-select" id="sStatus" onchange="filterTable()">
                <option value="all"><?php esc_html_e('Status', 'cv-builder'); ?></option>
                <option value="active"><?php esc_html_e('Active', 'cv-builder'); ?></option>
                <option value="deactive"><?php esc_html_e('Deactive', 'cv-builder'); ?></option>
            </select>
        </div>
    </div>

    <?php
    $orders = wc_get_orders([
        'limit' => -1,
        'status' => ['completed', 'processing'],
    ]);

    if (!empty($orders)) {
        echo '<table id="dataTable" class="wp-list-table widefat fixed striped" style="margin-top: 20px;">';

        // Table header
        echo '<thead>
            <tr>
                <th>' . esc_html__('Order ID', 'cv-builder') . '</th>
                <th>' . esc_html__('Username', 'cv-builder') . '</th>
                <th>' . esc_html__('Product Name', 'cv-builder') . '</th>
                <th>' . esc_html__('Plan Name', 'cv-builder') . '</th>
                <th>' . esc_html__('CV Download', 'cv-builder') . '</th>
                <th>' . esc_html__('Billing Period', 'cv-builder') . '</th>
                <th>' . esc_html__('Total Downloads', 'cv-builder') . '</th>
                <th>' . esc_html__('Purchase Date', 'cv-builder') . '</th>
                <th>' . esc_html__('Expire Date', 'cv-builder') . '</th>
                <th>' . esc_html__('Status', 'cv-builder') . '</th>
            </tr>
        </thead>';
        echo '<tbody>';

        foreach ($orders as $order) {
            $order_id = $order->get_id();
            $order_total = $order->get_total();
            
            $purchase_date = $order->get_date_created();
            $formatted_purchase_date = $purchase_date ?
                $purchase_date->setTimezone(new \DateTimeZone(wp_timezone_string()))->format('Y-m-d') : esc_html__('N/A', 'cv-builder');

            $items = $order->get_items();
            foreach ($items as $item) {
                $product_id = $item->get_product_id();
                $product_name = $item->get_name();
                $plan_name = get_post_meta($product_id, '_subscription_plan_name', true);

                $cv_download = $order->get_meta( '_subscription_per_download', true );
                if ( $cv_download === '' || $cv_download === null || $cv_download === false ) {
                    $cv_download = get_post_meta( $product_id, '_subscription_per_download', true );
                    $cv_download = is_numeric( $cv_download ) ? (int) $cv_download : 0;
                    $order->update_meta_data( '_subscription_per_download', $cv_download );
                    $order->save();
                } else {
                    $cv_download = is_numeric( $cv_download ) ? (int) $cv_download : 0;
                }

                $order_total_downloads = (int) $order->get_meta('_total_downloads', true);

                $subscription_billing_period = (int) $order->get_meta('_subscription_billing_period', true);
                if (!$subscription_billing_period) {
                    $subscription_billing_period = get_post_meta($product_id, '_subscription_billing_period', true);
                    $order->update_meta_data('_subscription_billing_period', $subscription_billing_period);
                    $order->save();
                }

                $user_id = $order->get_customer_id();
                $user = get_user_by('id', $user_id);
                $username = $user ? $user->user_login : esc_html__('N/A', 'cv-builder');

                $product_id = $item->get_product_id();
                $product_name = $item->get_name();

                $expire_date = '';
                if($subscription_billing_period){
                    $billing_days = 0;
                    if ($subscription_billing_period == '1') {
                        $billing_days = 1;
                    } elseif ($subscription_billing_period == '30') {
                        $billing_days = 30;
                    } elseif ($subscription_billing_period == '90') {
                        $billing_days = 90;
                    } elseif ($subscription_billing_period == '183') {
                        $billing_days = 183;
                    } elseif ($subscription_billing_period == '365') {
                        $billing_days = 365;
                    }
                    if ($purchase_date && $billing_days) {
                        $purchase_date_obj = new \DateTime($formatted_purchase_date);
                        $purchase_date_obj->modify("+$billing_days days");
                        $newDate = $purchase_date_obj->format('Y-m-d');
                        $expire_date = $subscription_billing_period?$newDate:'';
                    }
                } else{
                    $expire_date = esc_html__('Unlimited', 'cv-builder');
                }
                $expireCheck = '';
                if(\DateTime::createFromFormat('Y-m-d', $expire_date) !== false){
                    $expireCheck = $expire_date;
                }
                $current_date = date("Y-m-d");

                if ($user_id) {
                    $user_data = get_userdata($user_id);
                    if (!in_array('cv_editor', (array) $user_data->roles)) {
                        continue;
                    }
                    $sdfdf = $cv_download >= 1 || $current_date <= $expireCheck?'active':'deactive';
                    echo '<tr products-name="'.$product_name.'" user-names="'.$username.'" plan-names="'.$plan_name.'" billing-period="'.$subscription_billing_period.'" s-status="'.$sdfdf.'" subs-cription="0" data-date="'.$formatted_purchase_date.'">';
                    echo '<td>' .$order_id.'</td>';
                    echo '<td>' .$username.'</td>';
                    echo '<td>' .$product_name.'</td>';
                    echo '<td>' . esc_html($plan_name ? $plan_name : esc_html__('N/A', 'cv-builder')) . ' (' . wp_kses_post(wc_price($order_total)) . ') </td>';
                    echo '<td class="cv-download-cell">' . esc_html($cv_download ? $cv_download-1 : esc_html__('N/A', 'cv-builder')) . '</td>';
                    $dayValid = $subscription_billing_period==1?' Day':' Days';
                    echo '<td>' . esc_html($subscription_billing_period ? ucfirst($subscription_billing_period) : esc_html__('N/A', 'cv-builder')) . $dayValid.'</td>';
                    echo '<td class="total-download-cell">' . esc_html($order_total_downloads) . '</td>';
                    echo '<td>' . esc_html($formatted_purchase_date) . '</td>';
                    echo '<td>' . esc_html($expire_date) . '</td>';
                    echo '<td>';
                        if ($cv_download >= 1 || $current_date <= $expireCheck) {
                            echo '<div class="bwd-active-text">'.esc_html__('Active', 'cv-builder').'</div>';
                        } else{
                            echo '<div class="bwd-deactive-text">'.esc_html__('Deactive', 'cv-builder').'</div>';
                        }
                    echo '</td>';
                }

                echo '</tr>';
            }
        }

        echo '</tbody>';
        echo '</table>';
    } else {
        echo '<p>' . esc_html__('You have no completed or processing orders.', 'cv-builder') . '</p>';
    }
    echo '</div>';
echo '</div>';