<?php
// ========================================
// مدیریت سفارشات (نسخه اصلاح‌شده و کامل)
// پروژه فروشگاه کیف‌لند
// ========================================
require_once '../config/database.php';
require_once '../config/settings.php';
require_once '../config/telegram.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

Auth::requireAdmin();
$db = Database::getInstance()->getConnection();
$pageTitle = 'مدیریت سفارشات | کیف‌لند';

$success = '';
$error = '';

// ========================================
// پردازش درخواست‌ها (POST)
// ========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // ۱. تغییر وضعیت سفارش
    if (isset($_POST['action']) && $_POST['action'] == 'update_status') {
        try {
            $id = (int)($_POST['order_id'] ?? 0);
            $status = $_POST['status'];
            
            $allowed_statuses = ['pending', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded'];
            if (!in_array($status, $allowed_statuses)) throw new Exception('وضعیت نامعتبر است.');

            $sql = "UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$status, $id]);
            
            Auth::logActivity('order_status', "تغییر وضعیت سفارش #$id به $status");
            $success = 'وضعیت سفارش با موفقیت بروزرسانی شد.';

            // اعلان تلگرام
            try {
                $telegram = new TelegramBot();
                if ($telegram->isConfigured()) {
                    $stmt_o = $db->prepare("SELECT order_number, full_name FROM orders o LEFT JOIN users u ON o.user_id = u.id WHERE o.id = ?");
                    $stmt_o->execute([$id]);
                    $oi = $stmt_o->fetch();
                    if ($oi) $telegram->sendOrderStatusUpdate($oi['order_number'], $status, $oi['full_name'] ?? '');
                }
            } catch (Exception $e) { error_log("Telegram error: " . $e->getMessage()); }
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }

    // ۲. لغو سفارش
    elseif (isset($_POST['action']) && $_POST['action'] == 'cancel_order') {
        try {
            $id = (int)($_POST['order_id'] ?? 0);
            $sql = "UPDATE orders SET status = 'cancelled', updated_at = NOW() WHERE id = ?";
            $db->prepare($sql)->execute([$id]);
            Auth::logActivity('order_cancel', "لغو سفارش #$id");
            $success = 'سفارش لغو شد.';
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
}

// ========================================
// دریافت داده‌ها و فیلترها
// ========================================
$status_filter = $_GET['status'] ?? '';
$search = trim($_GET['search'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 15;
$offset = ($page - 1) * $per_page;

// کوئری اصلی
$sql = "SELECT o.*, u.full_name as customer_name, u.email as customer_email 
        FROM orders o 
        LEFT JOIN users u ON o.user_id = u.id 
        WHERE 1=1";
$params = [];

if ($status_filter) {
    $sql .= " AND o.status = ?";
    $params[] = $status_filter;
}
if ($search) {
    $sql .= " AND (o.order_number LIKE ? OR u.full_name LIKE ? OR u.email LIKE ? OR o.shipping_phone LIKE ?)";
    $p = "%$search%";
    array_push($params, $p, $p, $p, $p);
}

// شمارش کل
$count_sql = preg_replace('/SELECT o\.\*, u\.full_name as customer_name, u\.email as customer_email/', 'SELECT COUNT(*)', $sql);
$stmt_count = $db->prepare($count_sql);
$stmt_count->execute($params);
$total_orders = $stmt_count->fetchColumn();
$total_pages = ceil($total_orders / $per_page);

// دریافت سفارشات
$sql .= " ORDER BY o.created_at DESC LIMIT ? OFFSET ?";
array_push($params, (int)$per_page, (int)$offset);
$stmt = $db->prepare($sql);
$stmt->execute($params);
$orders = $stmt->fetchAll();

// آمار کلی
$stats_stmt = $db->query("SELECT status, COUNT(*) as count FROM orders GROUP BY status");
$stats = $stats_stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// ========================================
// دریافت جزئیات سفارش (برای مودال)
// ========================================
$modal_order = null;
$modal_items = [];
if (isset($_GET['view_id'])) {
    $view_id = (int)$_GET['view_id'];
    $stmt_order = $db->prepare("SELECT o.*, u.full_name as customer_name, u.email as customer_email FROM orders o LEFT JOIN users u ON o.user_id = u.id WHERE o.id = ?");
    $stmt_order->execute([$view_id]);
    $modal_order = $stmt_order->fetch();

    if ($modal_order) {
        $stmt_items = $db->prepare("SELECT * FROM order_items WHERE order_id = ?");
        $stmt_items->execute([$view_id]);
        $modal_items = $stmt_items->fetchAll();
    }
}

include 'includes/admin-header.php';
?>

<style>
/* ========================================
   Orders Page - Complete CSS
   ======================================== */

/* Stats Bar */
.stats-bar {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 16px;
    margin-bottom: 24px;
}
.stat-box {
    background: var(--glass-bg);
    backdrop-filter: blur(20px);
    border: 1px solid var(--glass-border);
    border-radius: var(--radius-sm);
    padding: 16px;
    text-align: center;
    transition: all var(--transition-fast);
}
.stat-box:hover { transform: translateY(-2px); background: var(--glass-bg-light); }
.stat-box h3 { font-size: 24px; font-weight: 700; margin: 0; color: var(--primary); }
.stat-box p { font-size: 12px; color: var(--text-secondary); margin: 4px 0 0 0; }

/* Filters Bar */
.filters-bar {
    display: flex;
    gap: 12px;
    flex-wrap: wrap;
    align-items: flex-end;
    background: var(--glass-bg);
    backdrop-filter: blur(20px);
    padding: 16px;
    border-radius: var(--radius);
    border: 1px solid var(--glass-border);
    margin-bottom: 24px;
}
.filter-group { display: flex; flex-direction: column; gap: 6px; flex: 1; min-width: 200px; }
.filter-group label { font-size: 12px; font-weight: 600; color: var(--text-secondary); display: flex; align-items: center; gap: 6px; }
.filter-group label i { opacity: 0.7; font-size: 11px; }

.filter-group select, .filter-group input {
    padding: 10px 14px; border: 1px solid var(--glass-border); border-radius: var(--radius-sm);
    background: var(--glass-bg-light); font-family: 'Vazirmatn', sans-serif; font-size: 13px; color: var(--text-primary);
    transition: all var(--transition-fast); min-height: 44px;
}
.filter-group select:focus, .filter-group input:focus { 
    outline: none; border-color: var(--primary); 
    box-shadow: 0 0 0 3px rgba(0,122,255,0.15); 
    background: #fff;
}

/* Table Styles */
.table-responsive { overflow-x: auto; border-radius: var(--radius); margin-bottom: 20px; }
.data-table { width: 100%; border-collapse: collapse; min-width: 800px; }
.data-table thead th {
    text-align: right; padding: 14px 16px; font-size: 12px; font-weight: 600;
    color: var(--text-secondary); background: rgba(255,255,255,0.3); border-bottom: 1px solid var(--glass-border);
    white-space: nowrap; position: sticky; top: 0; z-index: 5;
}
.data-table tbody td {
    padding: 14px 16px; font-size: 13px; color: var(--text-primary); border-bottom: 0.5px solid rgba(255,255,255,0.15); vertical-align: middle;
}
.data-table tbody tr:hover { background: rgba(255,255,255,0.2); }

/* Status Badges */
.status { display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; }
.status.pending { background: #fff3cd; color: #856404; }
.status.processing { background: #cce5ff; color: #004085; }
.status.shipped { background: #e2e3e5; color: #383d41; }
.status.delivered { background: #d4edda; color: #155724; }
.status.cancelled { background: #f8d7da; color: #721c24; }

/* Action Buttons */
.action-btn-sm {
    width: 32px; height: 32px; border-radius: 8px; border: none;
    background: rgba(255,255,255,0.3); cursor: pointer; transition: all var(--transition-fast);
    display: inline-flex; align-items: center; justify-content: center; color: var(--text-secondary);
    font-size: 12px; margin-right: 4px;
}
.action-btn-sm:hover { background: var(--glass-hover); transform: scale(1.05); }
.action-btn-sm.view:hover { color: var(--primary); background: var(--primary-light); }
.action-btn-sm.cancel:hover { color: var(--danger); background: var(--danger-light); }

/* ========================================
   Buttons - Complete Definition
   ======================================== */
.btn {
    display: inline-flex; align-items: center; justify-content: center; gap: 8px;
    padding: 10px 20px; border-radius: var(--radius-sm); font-weight: 600;
    font-size: 14px; cursor: pointer; transition: all var(--transition-fast);
    border: none; min-height: 44px; font-family: 'Vazirmatn', sans-serif;
    text-decoration: none; line-height: 1;
}
.btn:active { transform: scale(0.98); }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }

.btn-primary { background: var(--primary); color: white; box-shadow: 0 4px 12px rgba(0, 122, 255, 0.25); }
.btn-primary:hover { background: var(--primary-hover); transform: translateY(-2px); box-shadow: 0 6px 16px rgba(0, 122, 255, 0.35); }

.btn-ghost { background: transparent; color: var(--text-secondary); border: 1px solid var(--glass-border); }
.btn-ghost:hover { background: var(--glass-hover); color: var(--text-primary); border-color: var(--text-secondary); }

.btn-sm { padding: 6px 12px; font-size: 12px; min-height: 36px; }

/* Modal Styles */
.modal-overlay {
    position: fixed; inset: 0; background: rgba(0,0,0,0.4); backdrop-filter: blur(6px);
    z-index: 2000; display: none; align-items: center; justify-content: center; opacity: 0; transition: opacity var(--transition-fast);
}
.modal-overlay.active { display: flex; opacity: 1; }
.modal-content {
    background: var(--glass-bg-light); backdrop-filter: var(--glass-blur); border: 1px solid var(--glass-border);
    border-radius: var(--radius-lg); width: 100%; max-width: 700px; max-height: 90vh; overflow-y: auto;
    box-shadow: var(--glass-shadow-lg); transform: scale(0.95); transition: transform var(--transition-fast);
}
.modal-overlay.active .modal-content { transform: scale(1); }
.modal-header { padding: 20px; border-bottom: 1px solid var(--glass-border); display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; background: inherit; z-index: 10; }
.modal-header h3 { margin: 0; font-size: 18px; }
.modal-close { background: none; border: none; font-size: 24px; color: var(--text-muted); cursor: pointer; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; border-radius: 50%; transition: 0.2s; }
.modal-close:hover { background: rgba(255,255,255,0.3); color: var(--danger); }
.modal-body { padding: 24px; }
.modal-footer { padding: 16px 20px; border-top: 1px solid var(--glass-border); display: flex; justify-content: flex-end; gap: 10px; position: sticky; bottom: 0; background: inherit; }

/* Modal Details */
.detail-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin-bottom: 24px; }
.detail-item label { font-size: 11px; color: var(--text-muted); display: block; margin-bottom: 4px; }
.detail-item span { font-size: 14px; font-weight: 600; color: var(--text-primary); display: block; }
.items-table { width: 100%; border-collapse: collapse; margin-top: 16px; }
.items-table th { text-align: right; padding: 10px; font-size: 12px; color: var(--text-secondary); border-bottom: 1px solid var(--glass-border); }
.items-table td { padding: 10px; font-size: 13px; border-bottom: 1px solid rgba(255,255,255,0.1); }

.form-control {
    padding: 10px 14px; border: 1px solid var(--glass-border); border-radius: 10px;
    font-family: 'Vazirmatn', sans-serif; font-size: 14px; background: var(--glass-bg);
    backdrop-filter: blur(15px); transition: all 0.2s; min-height: 44px;
}
.form-control:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(0,122,255,0.15); }
.form-select { appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%2386868B' d='M6 8L1 3h10z'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: left 14px center; padding-left: 32px; }
/* Responsive */
@media (max-width: 768px) {
    .stats-bar { grid-template-columns: repeat(2, 1fr); }
    .filters-bar { flex-direction: column; }
    .filter-group { width: 100%; min-width: 100%; }
    .detail-grid { grid-template-columns: 1fr; }
    .modal-content { margin: 10px; }
}
</style>

<main class="main-content">
    <header class="top-header">
        <button class="menu-toggle" id="menuToggle"><i class="fas fa-bars"></i></button>
        <div class="search-box"><i class="fas fa-search"></i><input type="text" placeholder="جستجو در سفارشات..."></div>
        <div class="header-actions">
            <span class="btn btn-ghost btn-sm"><i class="fas fa-shopping-cart"></i> <?= number_format($total_orders) ?> سفارش</span>
        </div>
    </header>

    <div class="dashboard-content">
        <div class="page-title">
            <h1>مدیریت سفارشات</h1>
            <p>بررسی وضعیت و مدیریت سفارشات مشتریان</p>
        </div>

        <?php if ($error): ?><div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div><?php endif; ?>
        <?php if ($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div><?php endif; ?>

        <!-- آمار -->
        <div class="stats-bar">
            <div class="stat-box"><h3><?= $stats['pending'] ?: 0 ?></h3><p>در انتظار</p></div>
            <div class="stat-box"><h3><?= $stats['processing'] ?: 0 ?></h3><p>پردازش</p></div>
            <div class="stat-box"><h3><?= $stats['shipped'] ?: 0 ?></h3><p>ارسال شده</p></div>
            <div class="stat-box"><h3><?= $stats['delivered'] ?: 0 ?></h3><p>تحویل شده</p></div>
        </div>

        <!-- فیلترها -->
        <form method="GET" class="filters-bar">
            <div class="filter-group">
                <label><i class="fas fa-search"></i> جستجو</label>
                <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="شماره سفارش، نام یا تلفن...">
            </div>
            <div class="filter-group">
                <label><i class="fas fa-filter"></i> وضعیت</label>
                <select name="status">
                    <option value="">همه وضعیت‌ها</option>
                    <option value="pending" <?= $status_filter == 'pending' ? 'selected' : '' ?>>در انتظار پرداخت</option>
                    <option value="processing" <?= $status_filter == 'processing' ? 'selected' : '' ?>>در حال پردازش</option>
                    <option value="shipped" <?= $status_filter == 'shipped' ? 'selected' : '' ?>>ارسال شده</option>
                    <option value="delivered" <?= $status_filter == 'delivered' ? 'selected' : '' ?>>تحویل داده شده</option>
                    <option value="cancelled" <?= $status_filter == 'cancelled' ? 'selected' : '' ?>>لغو شده</option>
                </select>
            </div>
            <div class="filter-group" style="flex: none; display: flex; gap: 8px; margin-top: 20px;">
                <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-filter"></i> اعمال</button>
                <a href="orders.php" class="btn btn-ghost btn-sm"><i class="fas fa-undo"></i> ریست</a>
            </div>
        </form>

        <!-- جدول سفارشات -->
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>شماره سفارش</th>
                        <th>مشتری</th>
                        <th>تاریخ</th>
                        <th>مبلغ کل</th>
                        <th>وضعیت</th>
                        <th style="width: 100px; text-align: center;">عملیات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $order): ?>
                    <tr>
                        <td><strong>#<?= htmlspecialchars($order['order_number']) ?></strong></td>
                        <td>
                            <div style="font-weight: 600;"><?= htmlspecialchars($order['customer_name'] ?: 'مهمان') ?></div>
                            <small style="color: var(--text-secondary);"><?= htmlspecialchars($order['customer_email'] ?: '') ?></small>
                        </td>
                        <td style="font-size: 12px; color: var(--text-secondary);"><?= jdate($order['created_at']) ?></td>
                        <td style="font-weight: 700; color: var(--primary);"><?= number_format($order['final_amount']) ?> تومان</td>
                        <td><span class="status <?= $order['status'] ?>"><?= getStatusText($order['status']) ?></span></td>
                        <td style="text-align: center;">
                            <button class="action-btn-sm view" onclick="viewOrder(<?= $order['id'] ?>)" title="مشاهده جزئیات"><i class="fas fa-eye"></i></button>
                            <?php if ($order['status'] !== 'cancelled' && $order['status'] !== 'delivered'): ?>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('آیا از لغو این سفارش مطمئن هستید؟');">
                                <input type="hidden" name="action" value="cancel_order">
                                <input type="hidden" name="order_id" value="<?= $order['id'] ?>">
                                <button type="submit" class="action-btn-sm cancel" title="لغو سفارش"><i class="fas fa-times"></i></button>
                            </form>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($orders)): ?><tr><td colspan="6" class="text-center text-muted py-4">سفارشی یافت نشد.</td></tr><?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- صفحه‌بندی -->
        <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?><a href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>" class="page-link"><i class="fas fa-chevron-right"></i></a><?php endif; ?>
            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <?php if ($i == 1 || $i == $total_pages || abs($page - $i) <= 2): ?>
                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>" class="page-link <?= $i == $page ? 'active' : '' ?>"><?= $i ?></a>
                <?php elseif (abs($page - $i) == 3): ?><span class="text-muted px-2">...</span><?php endif; ?>
            <?php endfor; ?>
            <?php if ($page < $total_pages): ?><a href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>" class="page-link"><i class="fas fa-chevron-left"></i></a><?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</main>

<!-- Modal: View Order Details -->
<div class="modal-overlay" id="orderModal">
    <div class="modal-content">
        <?php if ($modal_order): ?>
        <form method="POST">
            <input type="hidden" name="action" value="update_status">
            <input type="hidden" name="order_id" value="<?= $modal_order['id'] ?>">
            
            <div class="modal-header">
                <h3>جزئیات سفارش #<?= htmlspecialchars($modal_order['order_number']) ?></h3>
                <button type="button" class="modal-close" onclick="closeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="detail-grid">
                    <div class="detail-item"><label>مشتری</label><span><?= htmlspecialchars($modal_order['customer_name'] ?: 'مهمان') ?></span></div>
                    <div class="detail-item"><label>شماره تماس</label><span><?= htmlspecialchars($modal_order['shipping_phone']) ?></span></div>
                    <div class="detail-item"><label>آدرس</label><span><?= htmlspecialchars($modal_order['shipping_address'] . '، ' . $modal_order['shipping_city']) ?></span></div>
                    <div class="detail-item"><label>روش پرداخت</label><span><?= htmlspecialchars($modal_order['payment_method'] ?: 'نامشخص') ?></span></div>
                    <div class="detail-item"><label>تاریخ ثبت</label><span><?= jdate($modal_order['created_at']) ?></span></div>
                    <div class="detail-item">
                        <label>وضعیت سفارش</label>
                        <select name="status" class="form-control" style="margin-top: 4px;">
                            <option value="pending" <?= $modal_order['status'] == 'pending' ? 'selected' : '' ?>>در انتظار پرداخت</option>
                            <option value="processing" <?= $modal_order['status'] == 'processing' ? 'selected' : '' ?>>در حال پردازش</option>
                            <option value="shipped" <?= $modal_order['status'] == 'shipped' ? 'selected' : '' ?>>ارسال شده</option>
                            <option value="delivered" <?= $modal_order['status'] == 'delivered' ? 'selected' : '' ?>>تحویل داده شده</option>
                            <option value="cancelled" <?= $modal_order['status'] == 'cancelled' ? 'selected' : '' ?>>لغو شده</option>
                        </select>
                    </div>
                </div>

                <h4 style="margin-bottom: 10px; font-size: 14px;">لیست محصولات</h4>
                <table class="items-table">
                    <thead>
                        <tr><th>محصول</th><th>تعداد</th><th>قیمت واحد</th><th>جمع</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($modal_items as $item): ?>
                        <tr>
                            <td><?= htmlspecialchars($item['product_name']) ?></td>
                            <td><?= $item['quantity'] ?></td>
                            <td><?= number_format($item['price']) ?></td>
                            <td><?= number_format($item['subtotal']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3" style="text-align: left; font-weight: 700;">مبلغ کل:</td>
                            <td style="font-weight: 700; color: var(--primary);"><?= number_format($modal_order['final_amount']) ?> تومان</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost" onclick="closeModal()">بستن</button>
                <button type="submit" class="btn btn-primary">ذخیره تغییرات</button>
            </div>
        </form>
        <?php else: ?>
        <div class="modal-body text-center p-5">
            <i class="fas fa-spinner fa-spin fa-2x" style="color: var(--primary);"></i>
            <p style="margin-top: 16px;">در حال بارگذاری...</p>
        </div>
        <?php endif; ?>
    </div>
</div>

<script src="assets/js/script.js"></script>
<script>
const modal = document.getElementById('orderModal');

function viewOrder(id) {
    // تغییر URL و رفرش صفحه برای لود اطلاعات PHP
    window.location.href = 'orders.php?view_id=' + id;
}

function closeModal() {
    // ۱. بستن انیمیشن مودال
    modal.classList.remove('active');
    
    // ۲. پاک کردن کامل پارامتر view_id از URL بدون رفرش صفحه (جلوگیری از باز شدن مجدد)
    const url = new URL(window.location);
    url.searchParams.delete('view_id');
    window.history.replaceState({}, '', url);
}

// باز کردن خودکار مودال اگر پارامتر در URL وجود دارد
<?php if (isset($_GET['view_id']) && $modal_order): ?>
window.onload = function() { 
    modal.classList.add('active'); 
};
<?php endif; ?>
</script>

<?php include 'includes/admin-footer.php'; ?>