<?php
session_start();
require_once '../config/database.php';
require_once '../includes/email_service.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_status') {
        $orderId = (int)($_POST['order_id'] ?? 0);
        $status = $_POST['status'] ?? '';
        
        if ($orderId > 0 && in_array($status, ['pending', 'completed', 'cancelled'])) {
            // Check if order is sent to SMM
            $stmt = $pdo->query("SELECT setting_value FROM app_settings WHERE setting_key = 'orders_sent_to_smm'");
            $smmData = $stmt->fetchColumn();
            $sentToSmm = [];
            if ($smmData) {
                $sentToSmm = json_decode($smmData, true) ?: [];
            }
            
            if (in_array($orderId, $sentToSmm) && $status === 'cancelled') {
                $error = "این سفارش به SMM ارسال شده و فقط توسط SMM قابل کنسل است";
            } else {
                // Get order details before updating
                $stmt = $pdo->prepare("SELECT user_id, total_coins, coin_type, status FROM orders WHERE id = ?");
                $stmt->execute([$orderId]);
                $order = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($order) {
                    $emailPayload = null;
                    $pdo->beginTransaction();
                    
                    try {
                        // Update order status
                        $stmt = $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?");
                        $stmt->execute([$status, $orderId]);
                        
                        // If order is being cancelled, refund coins
                        if ($status === 'cancelled' && $order['status'] !== 'cancelled') {
                            $userId = $order['user_id'];
                            $totalCoins = $order['total_coins'];
                            $coinType = $order['coin_type'];
                            
                            // Refund coins to user
                            if ($coinType === 'free') {
                                $stmt = $pdo->prepare("UPDATE users SET free_coins = free_coins + ? WHERE id = ?");
                            } else {
                                $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
                            }
                            $stmt->execute([$totalCoins, $userId]);
                            
                            // Add refund transaction record
                            $stmt = $pdo->prepare("
                                INSERT INTO transactions (user_id, type, amount, coin_type, description, created_at) 
                                VALUES (?, 'refund', ?, ?, 'Order cancellation refund', NOW())
                            ");
                            $stmt->execute([$userId, $totalCoins, $coinType]);
                        }

                        if ($order['status'] !== $status && in_array($status, ['cancelled', 'completed'], true)) {
                            $stmt = $pdo->prepare("
                                SELECT o.id, o.total_coins, o.quantity, u.id AS user_id, u.email, u.full_name, p.name AS product_name
                                FROM orders o
                                JOIN users u ON u.id = o.user_id
                                JOIN products p ON p.id = o.product_id
                                WHERE o.id = ?
                            ");
                            $stmt->execute([$orderId]);
                            $emailPayload = $stmt->fetch(PDO::FETCH_ASSOC);
                        }
                        
                        $pdo->commit();
                        $success = "وضعیت سفارش با موفقیت تغییر کرد" . ($status === 'cancelled' ? " و سکه‌ها برگردانده شد" : "");

                        if ($emailPayload && !empty($emailPayload['email'])) {
                            try {
                                if ($status === 'cancelled') {
                                    sendSystemEmail(
                                        $pdo,
                                        'order_cancelled',
                                        $emailPayload['email'],
                                        [
                                            'full_name' => $emailPayload['full_name'],
                                            'order_id' => $emailPayload['id'],
                                            'product_name' => $emailPayload['product_name'],
                                            'total_coins' => $emailPayload['total_coins']
                                        ],
                                        [
                                            'triggered_by' => 'admin_order_status',
                                            'context' => ['order_id' => $orderId, 'status' => $status, 'admin_id' => $_SESSION['admin_id']]
                                        ]
                                    );
                                } elseif ($status === 'completed') {
                                    sendSystemEmail(
                                        $pdo,
                                        'purchase_success',
                                        $emailPayload['email'],
                                        [
                                            'full_name' => $emailPayload['full_name'],
                                            'item_name' => $emailPayload['product_name'],
                                            'quantity' => $emailPayload['quantity'],
                                            'amount_text' => number_format($emailPayload['total_coins']) . ' سکه'
                                        ],
                                        [
                                            'triggered_by' => 'admin_order_status',
                                            'context' => ['order_id' => $orderId, 'status' => $status, 'admin_id' => $_SESSION['admin_id']]
                                        ]
                                    );
                                }
                            } catch (Exception $e) {
                                error_log("Order status email error: " . $e->getMessage());
                            }
                        }
                        
                    } catch (Exception $e) {
                        $pdo->rollBack();
                        $error = "خطا در تغییر وضعیت سفارش: " . $e->getMessage();
                    }
                } else {
                    $error = "سفارش یافت نشد";
                }
            }
        }
    } elseif ($action === 'delete_order') {
        $orderId = (int)($_POST['order_id'] ?? 0);
        
        if ($orderId > 0) {
            $stmt = $pdo->prepare("DELETE FROM orders WHERE id = ?");
            if ($stmt->execute([$orderId])) {
                $success = "سفارش با موفقیت حذف شد";
            } else {
                $error = "خطا در حذف سفارش";
            }
        }
    }
}

// Get orders with pagination
$page = (int)($_GET['page'] ?? 1);
$limit = 20;
$offset = ($page - 1) * $limit;

$stmt = $pdo->query("SELECT COUNT(*) FROM orders");
$totalOrders = $stmt->fetchColumn();
$totalPages = ceil($totalOrders / $limit);

$stmt = $pdo->prepare("
    SELECT o.id, o.quantity, o.total_coins, o.status, o.created_at, o.telegram_link, o.coin_type,
           u.username, u.email, u.full_name,
           p.name as product_name, p.price_coins as product_price
    FROM orders o
    JOIN users u ON o.user_id = u.id
    JOIN products p ON o.product_id = p.id
    ORDER BY o.created_at DESC
    LIMIT " . (int)$limit . " OFFSET " . (int)$offset
);
$stmt->execute();
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $pdo->query("SELECT setting_value FROM app_settings WHERE setting_key = 'orders_sent_to_smm'");
$smmData = $stmt->fetchColumn();
$sentToSmm = [];
if ($smmData) {
    $sentToSmm = json_decode($smmData, true) ?: [];
}

// Get statistics
$stmt = $pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'completed'");
$completedOrders = $stmt->fetchColumn();

$stmt = $pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'pending'");
$pendingOrders = $stmt->fetchColumn();

$stmt = $pdo->query("SELECT SUM(total_coins) FROM orders WHERE status = 'completed'");
$totalRevenue = $stmt->fetchColumn() ?: 0;
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مدیریت سفارشات - پنل مدیریت</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="assets/css/admin.css" rel="stylesheet">
</head>
<body class="admin-app">
    <?php include 'includes/menu.php'; ?>
    <?php include 'includes/header_bar.php'; ?>

    <main class="main">
        <div class="main-content">
                <?php
                $admin_page_title = 'مدیریت سفارشات';
                $admin_page_icon = 'fas fa-shopping-cart';
                include 'includes/topbar.php';
                ?>

                <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i>
                        <?= htmlspecialchars($success) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        <?= htmlspecialchars($error) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card stat-card info">
                            <div class="card-body text-center">
                                <i class="fas fa-shopping-cart fa-2x mb-2"></i>
                                <h4><?= number_format($totalOrders) ?></h4>
                                <p class="mb-0">کل سفارشات</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card success">
                            <div class="card-body text-center">
                                <i class="fas fa-check-circle fa-2x mb-2"></i>
                                <h4><?= number_format($completedOrders) ?></h4>
                                <p class="mb-0">سفارشات تکمیل شده</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card warning">
                            <div class="card-body text-center">
                                <i class="fas fa-clock fa-2x mb-2"></i>
                                <h4><?= number_format($pendingOrders) ?></h4>
                                <p class="mb-0">سفارشات در انتظار</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card">
                            <div class="card-body text-center">
                                <i class="fas fa-coins fa-2x mb-2"></i>
                                <h4><?= number_format($totalRevenue) ?></h4>
                                <p class="mb-0">درآمد کل (سکه)</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Orders Table -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">لیست سفارشات</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>کاربر</th>
                                        <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): ?>
                                    <tr>
                                        <td><?= $order['id'] ?></td>
                                        <td>
                                            <strong><?= htmlspecialchars($order['full_name']) ?></strong>
                                            <br><small class="text-muted">@<?= htmlspecialchars($order['username']) ?></small>
                                            <br><small class="text-muted"><?= htmlspecialchars($order['email']) ?></small>
                                        </td>
                                        <td>
                                            <strong><?= htmlspecialchars($order['product_name']) ?></strong>
                                            <br><small class="text-muted"><?= number_format($order['product_price']) ?> سکه</small>
                                        </td>
                                        <td>
                                            <span class="badge bg-info"><?= $order['quantity'] ?></span>
                                        </td>
                                        <td><?= number_format($order['product_price']) ?> سکه</td>
                                        <td>
                                            <span class="badge bg-warning text-dark">
                                                <?= number_format($order['total_coins']) ?> سکه
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($order['coin_type'] === 'free'): ?>
                                                <span class="badge bg-warning text-dark">
                                                    <i class="fas fa-star me-1"></i>سکه‌های رایگان
                                                </span>
                                            <?php else: ?>
                                                <span class="badge bg-primary text-white">
                                                    <i class="fas fa-coins me-1"></i>سکه‌های معمولی
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a href="https://<?= htmlspecialchars($order['telegram_link']) ?>" target="_blank" class="text-decoration-none">
                                                <i class="fab fa-telegram me-1"></i><?= htmlspecialchars($order['telegram_link']) ?>
                                            </a>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?= $order['status'] === 'completed' ? 'success' : ($order['status'] === 'pending' ? 'warning' : 'danger') ?>">
                                                <?= $order['status'] === 'completed' ? 'تکمیل شده' : ($order['status'] === 'pending' ? 'در انتظار' : 'لغو شده') ?>
                                            </span>
                                        </td>
                                        <td><?= date('Y/m/d H:i', strtotime($order['created_at'])) ?></td>
                                        <td>
                                            <?php 
                                            $isSentToSmm = in_array($order['id'], $sentToSmm);
                                            if ($isSentToSmm): ?>
                                                <span class="badge bg-info mb-2 d-block">📤 ارسال شده به SMM</span>
                                            <?php endif; ?>
                                            <div class="btn-group" role="group">
                                                <?php if ($order['status'] === 'pending' && !$isSentToSmm): ?>
                                                    <button type="button" class="btn btn-sm btn-primary" 
                                                            data-bs-toggle="modal" data-bs-target="#updateStatusModal" 
                                                            data-order-id="<?= $order['id'] ?>" 
                                                            data-current-status="<?= $order['status'] ?>">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                <?php elseif ($isSentToSmm): ?>
                                                    <button type="button" class="btn btn-sm btn-secondary" disabled title="این سفارش به SMM ارسال شده و فقط توسط SMM قابل کنسل است">
                                                        <i class="fas fa-lock"></i>
                                                    </button>
                                                <?php else: ?>
                                                    <button type="button" class="btn btn-sm btn-primary" 
                                                            data-bs-toggle="modal" data-bs-target="#updateStatusModal" 
                                                            data-order-id="<?= $order['id'] ?>" 
                                                            data-current-status="<?= $order['status'] ?>">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                <?php endif; ?>
                                                <button type="button" class="btn btn-sm btn-danger" 
                                                        onclick="deleteOrder(<?= $order['id'] ?>)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <?php if ($totalPages > 1): ?>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center">
                                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                                <li class="page-item <?= $i === $page ? 'active' : '' ?>">
                                    <a class="page-link" href="?page=<?= $i ?>"><?= $i ?></a>
                                </li>
                                <?php endfor; ?>
                            </ul>
                        </nav>
                        <?php endif; ?>
                    </div>
                </div>
        </div>
    </main>

    <!-- Update Status Modal -->
    <div class="modal fade" id="updateStatusModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">تغییر وضعیت سفارش</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="update_status">
                        <input type="hidden" name="order_id" id="updateOrderId">
                        
                        <div class="mb-3">
                            <label for="status" class="form-label">وضعیت جدید</label>
                            <select class="form-control" id="status" name="status" required>
                                <option value="pending">در انتظار</option>
                                <option value="completed">تکمیل شده</option>
                                <option value="cancelled">لغو شده</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                        <button type="submit" class="btn btn-primary">تغییر وضعیت</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <?php include 'includes/admin_shell_scripts.php'; ?>
    <script>
        // Update Status Modal
        document.getElementById('updateStatusModal').addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var orderId = button.getAttribute('data-order-id');
            var currentStatus = button.getAttribute('data-current-status');
            
            document.getElementById('updateOrderId').value = orderId;
            document.getElementById('status').value = currentStatus;
        });

        // Delete Order
        function deleteOrder(orderId) {
            if (confirm('آیا از حذف این سفارش اطمینان دارید؟')) {
                var form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_order">
                    <input type="hidden" name="order_id" value="${orderId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html>
