<?php
if ( ! defined( 'ABSPATH' ) ) exit;

use Anbarak\Input;
add_action('wp_ajax_anbarak_get_admin_orders', 'anbarak_ajax_render_admin_orders');
add_action('wp_ajax_anbarak_get_order_details', 'anbarak_ajax_get_order_details');
add_action('wp_ajax_anbarak_get_customer_data', 'anbarak_ajax_get_customer_data');
add_action('wp_ajax_anbarak_update_customer_info', 'anbarak_ajax_update_customer_info');
add_action('wp_ajax_anbarak_cancel_order', 'anbarak_ajax_cancel_order');
add_action('wp_ajax_anbarak_get_provinces', 'anbarak_ajax_get_provinces');

function anbarak_ajax_render_admin_orders()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access(false);

    $base = admin_url('admin.php?page=anbarak');

    $date_from = anbarak_timestamp_param('date-from', 0, 'get');
    $date_to = anbarak_timestamp_param('date-to', 0, 'get');
    $status = anbarak_get_param('order-status');
    $current_page = max(1, (int) anbarak_get_param('page'));

    if (!in_array($status, ['completed', 'cancelled', 'processing'])) {
        $status = [];
    } else {
        $status = [$status];
    }

    if ($per_page = anbarak_get_param('ipp')) {
        $per_page = max(1, (int) $per_page);
        setcookie('anbarak_admin_orders_ipp', $per_page, time() + (20 * 365 * 24 * 60 * 60));
    } else {
        $per_page = isset($_COOKIE['anbarak_admin_orders_ipp']) ? max(1, (int) sanitize_text_field(wp_unslash($_COOKIE['anbarak_admin_orders_ipp']))) : 2;
    }

    $offset = ($current_page - 1) * $per_page;

    $result = anbarak_get_admin_orders($per_page,  $current_page, $status, $date_from, $date_to);

    $orders = $result['orders'];
    $total_orders  = $result['total'];

    $total_price = 0;
?>
    <div data-filter-form="frm-admin-orders">
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th class="">#</th>
                        <th class=""><?php esc_html_e('Order ID', 'anbarak') ?></th>
                        <th class=""><?php esc_html_e('Date', 'anbarak') ?></th>
                        <th class=""><?php esc_html_e('Customer', 'anbarak') ?></th>
                        <th class=""><?php esc_html_e('Total', 'anbarak') ?></th>
                        <th class=""><?php esc_html_e('Profit', 'anbarak') ?></th>
                        <th class=""><?php esc_html_e('Status', 'anbarak') ?></th>
                        <th class=""><?php esc_html_e('Actions', 'anbarak') ?></th>
                    </tr>
                </thead>
                <tbody id="admin-orders-holder">
                    <?php if (!empty($orders)): ?>
                        <?php $counter = $offset + 1; ?>
                        <?php foreach ($orders as $order): ?>
                            <?php
                            $order_total = (float) $order->get_total() - (float) $order->get_shipping_total();
                            $order_profit = $order_total - (float) $order->get_meta('_anbarak_total_buy_cost', true);
                            $total_price += (float) $order->get_total();
                            ?>
                            <tr class="hover:bg-gray-50">
                                <td><?php echo esc_html($counter); ?></td>
                                <td>#<?php echo esc_html($order->get_id()); ?></td>
                                <td class="whitespace-nowrap"><?php echo wp_kses_post(anbarak_datetime($order->get_date_created()->getTimestamp())) ?></td>
                                <td>
                                    <?php echo esc_html($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()); ?>
                                </td>
                                <td><?php echo wp_kses_post($order->get_formatted_order_total()); ?></td>
                                <td class="whitespace-nowrap ltr <?php echo $order_profit < 0 ? 'text-red-500' : ''; ?>"><?php echo wp_kses_post(wc_price($order_profit)); ?></td>
                                <td class="whitespace-nowrap">
                                    <span class="px-3 p-1 inline-flex leading-5 font-semibold rounded-full 
                                    <?php echo $order->get_status() === 'completed' ? 'bg-green-200 text-green-800' : ($order->get_status() === 'processing' ? 'bg-blue-200 text-blue-800' : ($order->get_status() === 'cancelled' ? 'bg-red-200 text-red-800' : 'bg-gray-100 text-gray-800')); ?>">
                                        <?php echo esc_html(anbarak_get_translated_order_status($order->get_status())); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="flex gap-x-2">
	                                        <button class="btn button anbarak-order-details" data-order-id="<?php echo esc_attr($order->get_id()); ?>"><?php esc_html_e('View', 'anbarak') ?></button>
	                                        <?php if (anbarak_user_is_admin_or_manager()): ?>
	                                            <button class="btn button anbarak-edit-customer" data-order-id="<?php echo esc_attr($order->get_id()); ?>"><?php esc_html_e('Edit', 'anbarak') ?></button>
	                                            <?php if ($order->get_status() !== 'cancelled'): ?>
	                                                <button class="btn button anbarak-cancel-order" data-order-id="<?php echo esc_attr($order->get_id()); ?>"><?php esc_html_e('Cancel Order', 'anbarak') ?></button>
	                                            <?php endif; ?>
	                                        <?php endif ?>
                                    </div>
                                </td>
                            </tr>
                            <?php $counter++; ?>
                        <?php endforeach; ?>
                        <tr class="hover:bg-gray-50">
                            <td colspan="8" class="ps-6 pe-6 py-5 text-end text-sm text-gray-500">
                                <?php esc_html_e('Total', 'anbarak') ?> <?php echo wp_kses_post(wc_price($total_price)) ?>
                            </td>
                        </tr>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="px-6 py-4 text-center text-sm text-gray-500"><?php esc_html_e('No orders found.', 'anbarak') ?></td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>


            <div class="footer-actions flex flex-col lg:flex-row gap-4">
                <?php

                anbarak_pagination(
                    $base,
                    $current_page,
                    $per_page,
                    $total_orders ?? 0
                ); ?>
            </div>
        </div>
    </div>

    <div class="micro-modal micromodal-slide" id="order-details-modal" aria-hidden="true">
        <div class="modal__overlay" tabindex="-1" data-micromodal-close>
            <div class="modal__container box bg-white rounded-lg shadow-xl" role="dialog" aria-modal="true" style="max-width: 800px;">
                <header class="modal__header">
                    <h2 class="modal__title text-lg font-semibold text-gray-900"><?php esc_html_e('Order Information', 'anbarak') ?></h2>
                    <button class="modal__close" type="button" aria-label="Close modal" data-micromodal-close></button>
                </header>
                <main class="modal__content" id="order-details-content">
                </main>
            </div>
        </div>
    </div>

    <div class="micro-modal micromodal-slide" id="edit-customer-modal" aria-hidden="true">
        <div class="modal__overlay" tabindex="-1" data-micromodal-close>
            <div class="modal__container box bg-white rounded-lg shadow-xl" role="dialog" aria-modal="true" style="max-width: 700px;">
                <header class="modal__header">
                    <h2 class="modal__title text-lg font-semibold text-gray-900"><?php esc_html_e('Edit Customer Information', 'anbarak') ?></h2>
                    <button class="modal__close p-2 text-gray-400 hover:text-gray-600" type="button" aria-label="Close modal" data-micromodal-close></button>
                </header>
                <main class="modal__content">
                    <form id="edit-customer-form">
                        <input type="hidden" id="edit-order-id" name="order_id">

                        <div class="mb-6">
                            <h3 class="text-md font-semibold text-gray-900 mb-4"><?php esc_html_e('Personal Information', 'anbarak') ?></h3>
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <?php echo wp_kses_post(Input::render([
                                        'name' => 'billing_first_name',
                                        'id' => 'billing_first_name',
                                        'parent_class' => 'w-full',
                                        'label' => esc_html__('Name', 'anbarak'),
                                    ])); ?>
                                </div>
                                <div>
                                    <?php echo wp_kses_post(Input::render([
                                        'name' => 'billing_last_name',
                                        'id' => 'billing_last_name',
                                        'parent_class' => 'w-full',
                                        'label' => esc_html__('Last Name', 'anbarak'),
                                    ])); ?>
                                </div>
                            </div>
                        </div>

                        <div class="mb-6">
                            <h3 class="text-md font-semibold text-gray-900 mb-4"><?php esc_html_e('Contact Information', 'anbarak') ?></h3>
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <?php echo wp_kses_post(Input::render([
                                        'name' => 'billing_email',
                                        'id' => 'billing_email',
                                        'parent_class' => 'w-full',
                                        'label' => esc_html__('Email', 'anbarak'),
                                    ])); ?>
                                </div>
                                <div>
                                    <?php echo wp_kses_post(Input::render([
                                        'name' => 'billing_phone',
                                        'id' => 'billing_phone',
                                        'parent_class' => 'w-full',
                                        'label' => esc_html__('Phone', 'anbarak'),
                                    ])); ?>
                                </div>
                            </div>
                        </div>

                        <div class="mb-6">
                            <h3 class="text-md font-semibold text-gray-900 mb-4"><?php esc_html_e('Address Information', 'anbarak') ?></h3>

                            <?php if (anbarak_get_option('country_selector_mode', 'default') === 'dropdown'): ?>
                            <div class="mb-4">
                                <label for="billing_country" class="block text-sm font-medium text-gray-700 mb-1"><?php esc_html_e('Country', 'anbarak') ?></label>
                                <select id="billing_country" name="billing_country" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                    <option value=""><?php esc_html_e('Select Country', 'anbarak') ?></option>
                                    <?php
                                    $countries = WC()->countries->get_shipping_countries();
                                    asort($countries);
                                    foreach ($countries as $code => $name) {
                                        echo '<option value="' . esc_attr($code) . '">' . esc_html($name) . '</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                            <?php endif; ?>

                            <div class="mb-4">
                                <label for="billing_state" class="block text-sm font-medium text-gray-700 mb-1"><?php esc_html_e('Province', 'anbarak') ?></label>
                                <select id="billing_state" name="billing_state" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                    <option value=""><?php esc_html_e('Select Province', 'anbarak') ?></option>
                                    <?php

                                    $order_country = anbarak_get_order_default_country();
                                    $provinces = anbarak_wc_provinces($order_country);

                                    foreach ($provinces as $code => $province) {
                                        echo '<option value="' . esc_attr($code) . '">' . esc_html($province) . '</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="mb-4">
                                <?php echo wp_kses_post(Input::render([
                                    'name' => 'billing_city',
                                    'id' => 'billing_city',
                                    'parent_class' => 'w-full',
                                    'label' => esc_html__('City', 'anbarak'),
                                ])); ?>
                            </div>
                            <div class="mb-4">
                                <label for="billing_address_1" class="block text-sm font-medium text-gray-700 mb-1"><?php esc_html_e('Address', 'anbarak') ?></label>
                                <textarea id="billing_address_1" name="billing_address_1" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500"></textarea>
                            </div>
                            <div class="mb-4">
                                <label for="billing_address_2" class="block text-sm font-medium text-gray-700 mb-1"><?php esc_html_e('Additional Address (Optional)', 'anbarak') ?></label>
                                <textarea id="billing_address_2" name="billing_address_2" rows="2" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-indigo-500"></textarea>
                            </div>
                            <div class="mb-4">
                                <?php echo wp_kses_post(Input::render([
                                    'name' => 'billing_postcode',
                                    'id' => 'billing_postcode',
                                    'parent_class' => 'w-full',
                                    'label' => esc_html__('Postcode', 'anbarak'),
                                ])); ?>
                            </div>
                        </div>
                        <div class="flex gap-3 pt-4 border-t border-gray-200">
<button type="submit" class="button button--primary">
                                 <?php esc_html_e('Save Changes', 'anbarak') ?>
                             </button>
                             <button type="button" onclick="MicroModal.close('edit-customer-modal')" class="button">
                                 <?php esc_html_e('Cancel', 'anbarak') ?>
                             </button>
                        </div>
                    </form>
                </main>
            </div>
        </div>
    </div>

<?php
    wp_die();
}


function anbarak_ajax_get_order_details()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access();

    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
    $order = wc_get_order($order_id);

    if (!$order) {
        wp_send_json_error(array('message' => esc_html__('Order not found.', 'anbarak')), 404);
    }

    $provinces = anbarak_wc_provinces();

    ob_start();
?>
    <div class="space-y-4">
        <div class="grid grid-cols-2 gap-4">
            <div>
                <h3 class="font-semibold text-gray-900"><?php esc_html_e('Order Information', 'anbarak') ?></h3>
                <p><?php esc_html_e('Order', 'anbarak') ?> #: <?php echo esc_html($order->get_id()); ?></p>
                <p><?php esc_html_e('Date', 'anbarak') ?>: <?php echo esc_html($order->get_date_created()->format('Y-m-d H:i')); ?></p>
                <p><?php esc_html_e('Status', 'anbarak') ?>: <?php echo esc_html(ucfirst($order->get_status())); ?></p>
                <?php if (anbarak_user_is_admin_or_manager()): ?>
                    <p><?php esc_html_e('Total', 'anbarak') ?>: <?php echo wp_kses_post($order->get_formatted_order_total()); ?></p>
                <?php endif ?>
            </div>
            <div>
                <h3 class="font-semibold text-gray-900"><?php esc_html_e('Customer Information', 'anbarak') ?></h3>
                <p><?php esc_html_e('Name', 'anbarak') ?>: <?php echo esc_html($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()); ?></p>
                <p><?php esc_html_e('Phone', 'anbarak') ?>: <?php echo esc_html($order->get_billing_phone()); ?></p>
                <p><?php esc_html_e('Email', 'anbarak') ?>: <?php echo esc_html($order->get_billing_email()); ?></p>

                <p><?php esc_html_e('Address', 'anbarak') ?>: <?php echo esc_html($order->get_billing_address_1()); ?></p>

                <?php if ($order->get_billing_address_2()) : ?>
                    <p><?php esc_html_e('Address 2', 'anbarak') ?>: <?php echo esc_html($order->get_billing_address_2()); ?></p>
                <?php endif; ?>

                <p><?php esc_html_e('City', 'anbarak') ?>: <?php echo esc_html($order->get_billing_city()); ?></p>
                <p><?php esc_html_e('State', 'anbarak') ?>: <?php echo esc_html($order->get_billing_state()); ?></p>
                <p><?php esc_html_e('Postal Code', 'anbarak') ?>: <?php echo esc_html($order->get_billing_postcode()); ?></p>
                <p><?php esc_html_e('Country', 'anbarak') ?>: <?php echo esc_html($order->get_billing_country()); ?></p>
            </div>
        </div>

        <div>
            <h3 class="font-semibold mb-2 text-gray-900"><?php esc_html_e('Order Items', 'anbarak') ?></h3>
            <div class="border border-gray-200 rounded-md">
                <?php foreach ($order->get_items() as $item): ?>
                    <?php

                    $can_see_order_item = true;

                    ?>
                    <div class="flex  flex-col justify-between gap-x-5 text-sm p-3 border-b border-gray-200 last:border-b-0">
                        <div class="w-full flex gap-x-5 justify-between">
                            <div class="flex gap-x-2 items-center">
                                <p class="font-medium text-sm"><?php echo esc_html($item->get_name()); ?></p>
                                <span class="text-xs text-gray-400 me-2">SKU: <?php echo esc_html($item->get_product()->get_sku() ?: '-'); ?></span>
                            </div>
                            <p class="font-medium"><?php echo wp_kses_post($order->get_formatted_line_subtotal($item)); ?></p>
                        </div>
                            <p class="text-sm text-gray-500"><?php esc_html_e('Quantity', 'anbarak') ?>: <?php echo esc_html($item->get_quantity()); ?></p>
  

                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
<?php
    $html = ob_get_clean();

    wp_send_json_success(array('html' => $html));
}

function anbarak_ajax_get_customer_data()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access();

    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
    $order = wc_get_order($order_id);

    if (!$order) {
        wp_send_json_error(array('message' => esc_html__('Order not found.', 'anbarak')), 404);
    }

    $data = array(
        'billing_first_name' => $order->get_billing_first_name(),
        'billing_last_name' => $order->get_billing_last_name(),
        'billing_email' => $order->get_billing_email(),
        'billing_phone' => $order->get_billing_phone(),
        'billing_country' => $order->get_billing_country(),
        'billing_state' => $order->get_billing_state(),
        'billing_city' => $order->get_billing_city(),
        'billing_address_1' => $order->get_billing_address_1(),
        'billing_address_2' => $order->get_billing_address_2(),
        'billing_postcode' => $order->get_billing_postcode(),
    );

    wp_send_json_success($data);
}

function anbarak_ajax_update_customer_info()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access();

    $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
    $order = wc_get_order($order_id);

    if (!$order) {
        wp_send_json_error(array('message' => esc_html__('Order not found.', 'anbarak')), 404);
    }

    // Update personal information
    if (isset($_POST['billing_first_name'])) $order->set_billing_first_name(sanitize_text_field(wp_unslash($_POST['billing_first_name'])));
    if (isset($_POST['billing_last_name'])) $order->set_billing_last_name(sanitize_text_field(wp_unslash($_POST['billing_last_name'])));
    if (isset($_POST['billing_email'])) $order->set_billing_email(sanitize_email(wp_unslash($_POST['billing_email'])));
    if (isset($_POST['billing_phone'])) $order->set_billing_phone(sanitize_text_field(wp_unslash($_POST['billing_phone'])));

    // Update address information
    if (!empty($_POST['billing_country'])) {
        $order->set_billing_country(sanitize_text_field(wp_unslash($_POST['billing_country'])));
    }
    if (isset($_POST['billing_state'])) $order->set_billing_state(sanitize_text_field(wp_unslash($_POST['billing_state'])));
    if (isset($_POST['billing_city'])) $order->set_billing_city(sanitize_text_field(wp_unslash($_POST['billing_city'])));
    if (isset($_POST['billing_address_1'])) $order->set_billing_address_1(sanitize_textarea_field(wp_unslash($_POST['billing_address_1'])));
    if (isset($_POST['billing_address_2'])) $order->set_billing_address_2(sanitize_textarea_field(wp_unslash($_POST['billing_address_2'])));
    if (isset($_POST['billing_postcode'])) $order->set_billing_postcode(sanitize_text_field(wp_unslash($_POST['billing_postcode'])));


    $order->save();

    wp_send_json_success();
}

function anbarak_ajax_cancel_order()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access();

    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
    $order = wc_get_order($order_id);

    if (!$order) {
        wp_send_json_error(array('message' => esc_html__('Order not found.', 'anbarak')), 404);
    }

    $order->update_status('cancelled', 'Order cancelled by user');

    wp_send_json_success();
}


function anbarak_ajax_get_provinces()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access();

    $country = sanitize_text_field(isset($_GET['country']) ? wp_unslash($_GET['country']) : '');

    if (empty($country)) {
        wp_send_json_success(['provinces' => []]);
        return;
    }

    $provinces = anbarak_wc_provinces($country);
    wp_send_json_success(['provinces' => $provinces]);
}
