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

global $wpdb;
$action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : 'list';
$order_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// پردازش تغییر وضعیت
if (isset($_POST['update_order_status']) && check_admin_referer('dima_update_order')) {
    $new_status = sanitize_text_field($_POST['order_status']);
    $checkout = Dima_Checkout::get_instance();
    $checkout->update_order_status($order_id, $new_status);
    echo '<div class="notice notice-success"><p>وضعیت سفارش بروزرسانی شد.</p></div>';
}

// مشاهده سفارش تکی
if ($action === 'view' && $order_id > 0) {
    $order = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}dima_orders WHERE id = %d", $order_id));
    $items = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}dima_order_items WHERE order_id = %d", $order_id));
    $customer = json_decode($order->customer_data, true);
    
    if (!$order) {
        echo '<div class="notice notice-error"><p>سفارش یافت نشد.</p></div>';
        return;
    }
    
    $status_labels = array('pending' => 'در انتظار', 'processing' => 'در حال پردازش', 'completed' => 'تکمیل شده', 'failed' => 'ناموفق', 'cancelled' => 'لغو شده', 'refunded' => 'مرجوع شده');
    ?>
    <div class="wrap">
        <h1>سفارش #<?php echo intval($order->id); ?></h1>
        <a href="<?php echo admin_url('admin.php?page=dima-shop-orders'); ?>" class="button">← بازگشت</a>
        
        <div class="dima-order-grid">
            <div class="dima-order-box">
                <h3>📋 اطلاعات سفارش</h3>
                <table class="form-table">
                    <tr><th>وضعیت:</th><td><?php echo $status_labels[$order->status] ?? $order->status; ?></td></tr>
                    <tr><th>مبلغ کل:</th><td><?php echo number_format($order->total_amount); ?> تومان</td></tr>
                    <tr><th>تخفیف:</th><td><?php echo number_format($order->discount_amount); ?> تومان</td></tr>
                    <tr><th>مبلغ نهایی:</th><td><strong><?php echo number_format($order->final_amount); ?> تومان</strong></td></tr>
                    <tr><th>درگاه:</th><td><?php echo esc_html($order->payment_method); ?></td></tr>
                    <tr><th>کد تراکنش:</th><td><code><?php echo esc_html($order->transaction_id); ?></code></td></tr>
                    <tr><th>تاریخ:</th><td><?php echo date_i18n('j F Y - H:i', strtotime($order->created_at)); ?></td></tr>
                </table>
                
                <form method="post" style="margin-top:20px;">
                    <?php wp_nonce_field('dima_update_order'); ?>
                    <label><strong>تغییر وضعیت:</strong></label>
                    <select name="order_status">
                        <?php foreach ($status_labels as $key => $label): ?>
                            <option value="<?php echo esc_attr($key); ?>" <?php selected($order->status, $key); ?>><?php echo $label; ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" name="update_order_status" class="button button-primary">بروزرسانی</button>
                </form>
            </div>
            
            <div class="dima-order-box">
                <h3>👤 اطلاعات مشتری</h3>
                <table class="form-table">
                    <tr><th>نام:</th><td><?php echo esc_html($customer['name'] ?? '-'); ?></td></tr>
                    <tr><th>موبایل:</th><td><?php echo esc_html($customer['phone'] ?? '-'); ?></td></tr>
                    <tr><th>ایمیل:</th><td><?php echo esc_html($customer['email'] ?? '-'); ?></td></tr>
                    <tr><th>استان:</th><td><?php echo esc_html($customer['province'] ?? '-'); ?></td></tr>
                    <tr><th>شهر:</th><td><?php echo esc_html($customer['city'] ?? '-'); ?></td></tr>
                    <tr><th>آدرس:</th><td><?php echo esc_html($customer['address'] ?? '-'); ?></td></tr>
                    <tr><th>کد پستی:</th><td><?php echo esc_html($customer['postal_code'] ?? '-'); ?></td></tr>
                </table>
            </div>
            
            <div class="dima-order-box full-width">
                <h3>️ آیتم‌های سفارش</h3>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr><th>محصول</th><th>تعداد</th><th>قیمت واحد</th><th>جمع</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($items as $item): 
                            $product = get_post($item->product_id);
                        ?>
                        <tr>
                            <td><?php echo $product ? esc_html($product->post_title) : 'حذف شده'; ?></td>
                            <td><?php echo intval($item->quantity); ?></td>
                            <td><?php echo number_format($item->price); ?> تومان</td>
                            <td><strong><?php echo number_format($item->price * $item->quantity); ?> تومان</strong></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <style>
    .dima-order-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 20px; }
    .dima-order-box { background: white; padding: 24px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); border: 1px solid #e5e7eb; }
    .dima-order-box h3 { margin: 0 0 20px 0; padding-bottom: 12px; border-bottom: 2px solid #f3f4f6; color: #1f2937; }
    .dima-order-box.full-width { grid-column: 1 / -1; }
    </style>
    <?php
    return;
}

// لیست سفارشات
$orders = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}dima_orders ORDER BY created_at DESC LIMIT 100");
$status_labels = array('pending' => 'در انتظار', 'processing' => 'در حال پردازش', 'completed' => 'تکمیل شده', 'failed' => 'ناموفق', 'cancelled' => 'لغو شده', 'refunded' => 'مرجوع شده');
$status_colors = array('pending' => '#f59e0b', 'processing' => '#3b82f6', 'completed' => '#10b981', 'failed' => '#ef4444', 'cancelled' => '#6b7280', 'refunded' => '#8b5cf6');
?>

<div class="wrap">
    <h1>🛒 سفارشات</h1>
    
    <?php if (empty($orders)): ?>
    <div class="empty-state">
        <div class="empty-icon">📭</div>
        <h3>هنوز سفارشی ثبت نشده است</h3>
    </div>
    <?php else: ?>
    <div class="table-responsive">
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th>شناسه</th>
                    <th>مشتری</th>
                    <th>مبلغ کل</th>
                    <th>تخفیف</th>
                    <th>نهایی</th>
                    <th>وضعیت</th>
                    <th>درگاه</th>
                    <th>تاریخ</th>
                    <th>عملیات</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orders as $order): 
                    $customer = json_decode($order->customer_data, true);
                ?>
                <tr>
                    <td><strong>#<?php echo intval($order->id); ?></strong></td>
                    <td><?php echo esc_html($customer['name'] ?? 'مهمان'); ?></td>
                    <td><?php echo number_format($order->total_amount); ?></td>
                    <td><?php echo number_format($order->discount_amount); ?></td>
                    <td><strong><?php echo number_format($order->final_amount); ?> تومان</strong></td>
                    <td>
                        <span style="background:<?php echo $status_colors[$order->status] ?? '#6b7280'; ?>; color:white; padding:4px 12px; border-radius:20px; font-size:12px; font-weight:600;">
                            <?php echo $status_labels[$order->status] ?? $order->status; ?>
                        </span>
                    </td>
                    <td><?php echo esc_html($order->payment_method); ?></td>
                    <td><?php echo date_i18n('j F Y', strtotime($order->created_at)); ?></td>
                    <td>
                        <a href="<?php echo admin_url('admin.php?page=dima-shop-orders&action=view&id=' . $order->id); ?>" class="button button-small">
                            مشاهده
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>