<?php
session_start();
require_once '../config/database.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 === 'add_product') {
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $priceCoins = (int)($_POST['price_coins'] ?? 0);
        $minOrder = max(1, (int)($_POST['min_order'] ?? 1));
        $categoryId = (int)($_POST['category_id'] ?? 0);
        $imageUrl = trim($_POST['image_url'] ?? '');
        
        if (empty($name) || $priceCoins <= 0 || $categoryId <= 0) {
            $error = 'نام محصول، قیمت و دسته‌بندی الزامی است';
        } else {
            // Get category name and check if it's a free coins category
            $stmt = $pdo->prepare("SELECT name, is_free_coins_category FROM categories WHERE id = ? AND is_active = 1");
            $stmt->execute([$categoryId]);
            $categoryData = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$categoryData) {
                $error = 'دسته‌بندی انتخاب شده نامعتبر است';
            } else {
                $category = $categoryData['name'];
                $coinType = $categoryData['is_free_coins_category'] ? 'free' : 'regular';
                
                $smmServiceId = !empty($_POST['smm_service_id']) ? (int)$_POST['smm_service_id'] : null;
                $stmt = $pdo->prepare("INSERT INTO products (name, description, price_coins, min_order, category, image_url, coin_type, smm_service_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                if ($stmt->execute([$name, $description, $priceCoins, $minOrder, $category, $imageUrl, $coinType, $smmServiceId])) {
                    $success = "محصول با موفقیت اضافه شد";
                } else {
                    $error = "خطا در اضافه کردن محصول";
                }
            }
        }
    } elseif ($action === 'edit_product') {
        $productId = (int)($_POST['product_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $priceCoins = (int)($_POST['price_coins'] ?? 0);
        $minOrder = max(1, (int)($_POST['min_order'] ?? 1));
        $categoryId = (int)($_POST['category_id'] ?? 0);
        $imageUrl = trim($_POST['image_url'] ?? '');
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        
        if ($productId <= 0 || empty($name) || $priceCoins <= 0 || $categoryId <= 0) {
            $error = 'اطلاعات محصول نامعتبر است';
        } else {
            // Get category name and check if it's a free coins category
            $stmt = $pdo->prepare("SELECT name, is_free_coins_category FROM categories WHERE id = ? AND is_active = 1");
            $stmt->execute([$categoryId]);
            $categoryData = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$categoryData) {
                $error = 'دسته‌بندی انتخاب شده نامعتبر است';
            } else {
                $category = $categoryData['name'];
                $coinType = $categoryData['is_free_coins_category'] ? 'free' : 'regular';
                
                $smmServiceId = !empty($_POST['smm_service_id']) ? (int)$_POST['smm_service_id'] : null;
                $stmt = $pdo->prepare("UPDATE products SET name = ?, description = ?, price_coins = ?, min_order = ?, category = ?, image_url = ?, is_active = ?, coin_type = ?, smm_service_id = ? WHERE id = ?");
                if ($stmt->execute([$name, $description, $priceCoins, $minOrder, $category, $imageUrl, $isActive, $coinType, $smmServiceId, $productId])) {
                    $success = "محصول با موفقیت ویرایش شد";
                } else {
                    $error = "خطا در ویرایش محصول";
                }
            }
        }
    } elseif ($action === 'delete_product') {
        $productId = (int)($_POST['product_id'] ?? 0);
        
        if ($productId > 0) {
            $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
            if ($stmt->execute([$productId])) {
                $success = "محصول با موفقیت حذف شد";
            } else {
                $error = "خطا در حذف محصول";
            }
        }
    }
}

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

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

$stmt = $pdo->prepare("SELECT id, name, description, price_coins, min_order, image_url, category, coin_type, smm_service_id, is_active, created_at FROM products ORDER BY created_at DESC LIMIT " . (int)$limit . " OFFSET " . (int)$offset);
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get categories for dropdown
$stmt = $pdo->query("SELECT id, name FROM categories WHERE is_active = 1 ORDER BY name");
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!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">
    <style>
        .product-image { max-width: 80px; max-height: 80px; object-fit: cover; }
    </style>
</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-box';
                $admin_page_actions = '<span class="badge rounded-pill admin-badge-soft me-2">' . number_format($totalProducts) . ' محصول</span>'
                    . '<button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addProductModal"><i class="fas fa-plus ms-1"></i>افزودن محصول</button>';
                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; ?>

                <!-- Products 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>تصویر</th>
                                        <th>نام محصول</th>
                                        <th>دسته‌بندی</th>
                                        <th>نوع سکه</th>
                                        <th>قیمت (سکه)</th>
                                        <th>حداقل سفارش</th>
                                        <th>وضعیت</th>
                                        <th>تاریخ ایجاد</th>
                                        <th>عملیات</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($products as $product): ?>
                                    <tr>
                                        <td>
                                            <?php if ($product['image_url']): ?>
                                                <img src="<?= htmlspecialchars($product['image_url']) ?>" alt="<?= htmlspecialchars($product['name']) ?>" class="product-image rounded">
                                            <?php else: ?>
                                                <div class="bg-light text-center product-image rounded d-flex align-items-center justify-content-center">
                                                    <i class="fas fa-image text-muted"></i>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <strong><?= htmlspecialchars($product['name']) ?></strong>
                                            <?php if ($product['description']): ?>
                                                <br><small class="text-muted"><?= htmlspecialchars(substr($product['description'], 0, 50)) ?>...</small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($product['category']): ?>
                                                <span class="badge bg-info"><?= htmlspecialchars($product['category']) ?></span>
                                            <?php else: ?>
                                                <span class="text-muted">بدون دسته</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($product['coin_type'] === 'free'): ?>
                                                <span class="badge bg-warning text-dark">
                                                    <i class="fas fa-gift 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>
                                            <span class="badge bg-warning text-dark">
                                                <?= number_format($product['price_coins']) ?> سکه
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-secondary">
                                                <?= number_format((int)$product['min_order']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?= $product['is_active'] ? 'success' : 'danger' ?>">
                                                <?= $product['is_active'] ? 'فعال' : 'غیرفعال' ?>
                                            </span>
                                        </td>
                                        <td><?= date('Y/m/d H:i', strtotime($product['created_at'])) ?></td>
                                        <td>
                                            <div class="btn-group" role="group">
                                                <button type="button" class="btn btn-sm btn-primary" 
                                                        data-bs-toggle="modal" data-bs-target="#editProductModal" 
                                                        data-product='<?= json_encode($product) ?>'>
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-danger" 
                                                        onclick="deleteProduct(<?= $product['id'] ?>, '<?= htmlspecialchars($product['name']) ?>')">
                                                    <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>

    <!-- Add Product Modal -->
    <div class="modal fade" id="addProductModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <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="add_product">
                        
                        <div class="row">
                            <div class="col-md-8">
                                <div class="mb-3">
                                    <label for="name" class="form-label">نام محصول *</label>
                                    <input type="text" class="form-control" id="name" name="name" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="price_coins" class="form-label">قیمت (سکه) *</label>
                                    <input type="number" class="form-control" id="price_coins" name="price_coins" min="1" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="min_order" class="form-label">حداقل سفارش *</label>
                                    <input type="number" class="form-control" id="min_order" name="min_order" min="1" value="1" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="category_id" class="form-label">دسته‌بندی *</label>
                                    <select class="form-control" id="category_id" name="category_id" required>
                                        <option value="">انتخاب کنید</option>
                                        <?php foreach ($categories as $category): ?>
                                        <option value="<?= htmlspecialchars($category['id']) ?>"><?= htmlspecialchars($category['name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="image_url" class="form-label">آدرس تصویر</label>
                                    <input type="url" class="form-control" id="image_url" name="image_url" placeholder="https://example.com/image.jpg">
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="smm_service_id" class="form-label">Service ID در SMM (اختیاری)</label>
                                    <input type="number" class="form-control" id="smm_service_id" name="smm_service_id" placeholder="مثال: 123">
                                    <div class="form-text">Service ID مربوط به این محصول در SMM را وارد کنید</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="description" class="form-label">توضیحات</label>
                            <textarea class="form-control" id="description" name="description" rows="4" placeholder="توضیحات محصول..."></textarea>
                        </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>

    <!-- Edit Product Modal -->
    <div class="modal fade" id="editProductModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <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="edit_product">
                        <input type="hidden" name="product_id" id="editProductId">
                        
                        <div class="row">
                            <div class="col-md-8">
                                <div class="mb-3">
                                    <label for="editName" class="form-label">نام محصول *</label>
                                    <input type="text" class="form-control" id="editName" name="name" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="editPriceCoins" class="form-label">قیمت (سکه) *</label>
                                    <input type="number" class="form-control" id="editPriceCoins" name="price_coins" min="1" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="editMinOrder" class="form-label">حداقل سفارش *</label>
                                    <input type="number" class="form-control" id="editMinOrder" name="min_order" min="1" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editCategoryId" class="form-label">دسته‌بندی *</label>
                                    <select class="form-control" id="editCategoryId" name="category_id" required>
                                        <option value="">انتخاب کنید</option>
                                        <?php foreach ($categories as $category): ?>
                                        <option value="<?= htmlspecialchars($category['id']) ?>"><?= htmlspecialchars($category['name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editImageUrl" class="form-label">آدرس تصویر</label>
                                    <input type="url" class="form-control" id="editImageUrl" name="image_url" placeholder="https://example.com/image.jpg">
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="editSmmServiceId" class="form-label">Service ID در SMM (اختیاری)</label>
                                    <input type="number" class="form-control" id="editSmmServiceId" name="smm_service_id" placeholder="مثال: 123">
                                    <div class="form-text">Service ID مربوط به این محصول در SMM را وارد کنید</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="editDescription" class="form-label">توضیحات</label>
                            <textarea class="form-control" id="editDescription" name="description" rows="4" placeholder="توضیحات محصول..."></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="editIsActive" name="is_active" checked>
                                <label class="form-check-label" for="editIsActive">
                                    محصول فعال است
                                </label>
                            </div>
                        </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>
            </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>
        // Edit Product Modal
        document.getElementById('editProductModal').addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var product = JSON.parse(button.getAttribute('data-product'));
            
            document.getElementById('editProductId').value = product.id;
            document.getElementById('editName').value = product.name;
            document.getElementById('editDescription').value = product.description;
            document.getElementById('editPriceCoins').value = product.price_coins;
            document.getElementById('editMinOrder').value = product.min_order || 1;
            document.getElementById('editImageUrl').value = product.image_url || '';
            document.getElementById('editSmmServiceId').value = product.smm_service_id || '';
            document.getElementById('editIsActive').checked = product.is_active == 1;
            
            // Set category - find the option with matching text
            var categorySelect = document.getElementById('editCategoryId');
            for (var i = 0; i < categorySelect.options.length; i++) {
                if (categorySelect.options[i].text === product.category) {
                    categorySelect.selectedIndex = i;
                    break;
                }
            }
        });

        // Delete Product
        function deleteProduct(productId, productName) {
            if (confirm('آیا از حذف محصول "' + productName + '" اطمینان دارید؟')) {
                var form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_product">
                    <input type="hidden" name="product_id" value="${productId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }


    </script>
</body>
</html>
