<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// Set proper encoding for Persian characters
header('Content-Type: text/html; charset=utf-8');
session_start();
require_once '../config/database.php';

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $name = $_POST['name'];
                $coins = (int)$_POST['coins'];
                $price = (float)$_POST['price'];
                $originalPrice = (float)$_POST['original_price'];
                $discount = (int)$_POST['discount'];
                $priority = (int)$_POST['priority'];
                $isPopular = isset($_POST['is_popular']) ? 1 : 0;
                $isSpecialOffer = isset($_POST['is_special_offer']) ? 1 : 0;
                $specialOfferEndTime = isset($_POST['special_offer_end_time']) && !empty($_POST['special_offer_end_time']) ? $_POST['special_offer_end_time'] : null;
                $specialOfferBgColor = isset($_POST['special_offer_bg_color']) ? $_POST['special_offer_bg_color'] : '#FF6B6B';
                $productId = trim($_POST['product_id'] ?? '');
                // اگر product_id خالی است، آن را NULL قرار دهیم
                $productId = empty($productId) ? null : $productId;
                
                $stmt = $pdo->prepare("INSERT INTO coin_packages (name, coins, price, original_price, discount, priority, is_popular, is_special_offer, special_offer_end_time, special_offer_bg_color, product_id, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)");
                $stmt->execute([$name, $coins, $price, $originalPrice, $discount, $priority, $isPopular, $isSpecialOffer, $specialOfferEndTime, $specialOfferBgColor, $productId]);
                
                header('Location: coin_packages.php?success=added');
                exit();
                break;
                
            case 'edit':
                $id = (int)$_POST['id'];
                $name = $_POST['name'];
                $coins = (int)$_POST['coins'];
                $price = (float)$_POST['price'];
                $originalPrice = (float)$_POST['original_price'];
                $discount = (int)$_POST['discount'];
                $priority = (int)$_POST['priority'];
                $isPopular = isset($_POST['is_popular']) ? 1 : 0;
                $isSpecialOffer = isset($_POST['is_special_offer']) ? 1 : 0;
                $productId = trim($_POST['product_id'] ?? '');
                // اگر product_id خالی است، آن را NULL قرار دهیم
                $productId = empty($productId) ? null : $productId;
                $specialOfferEndTime = isset($_POST['special_offer_end_time']) && !empty($_POST['special_offer_end_time']) ? $_POST['special_offer_end_time'] : null;
                $specialOfferBgColor = isset($_POST['special_offer_bg_color']) ? $_POST['special_offer_bg_color'] : '#FF6B6B';
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                
                $stmt = $pdo->prepare("UPDATE coin_packages SET name = ?, coins = ?, price = ?, original_price = ?, discount = ?, priority = ?, is_popular = ?, is_special_offer = ?, special_offer_end_time = ?, special_offer_bg_color = ?, product_id = ?, is_active = ? WHERE id = ?");
                $stmt->execute([$name, $coins, $price, $originalPrice, $discount, $priority, $isPopular, $isSpecialOffer, $specialOfferEndTime, $specialOfferBgColor, $productId, $isActive, $id]);
                
                header('Location: coin_packages.php?success=updated');
                exit();
                break;
                
            case 'delete':
                $id = (int)$_POST['id'];
                $stmt = $pdo->prepare("DELETE FROM coin_packages WHERE id = ?");
                $stmt->execute([$id]);
                
                header('Location: coin_packages.php?success=deleted');
                exit();
                break;
        }
    }
}

// Auto-disable expired special offers
$currentTime = new DateTime();
$stmt = $pdo->prepare("UPDATE coin_packages SET is_special_offer = 0 WHERE is_special_offer = 1 AND special_offer_end_time IS NOT NULL AND special_offer_end_time < ?");
$stmt->execute([$currentTime->format('Y-m-d H:i:s')]);

// Get all coin packages
$stmt = $pdo->query("SELECT * FROM coin_packages ORDER BY priority DESC, coins ASC");
$packages = $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>
        .table-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            font-weight: 600;
            padding: 16px;
        }
        
        .table td {
            padding: 16px;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            vertical-align: middle;
        }
        
        .table tbody tr:hover {
            background: rgba(102, 126, 234, 0.05);
        }
        
        .btn-action {
            border-radius: 8px;
            padding: 8px 16px;
            margin: 0 4px;
            transition: all 0.3s ease;
        }
        
        .btn-action:hover {
            transform: scale(1.05);
        }
        
        .badge-custom {
            border-radius: 20px;
            padding: 6px 12px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .modal-content {
            border-radius: 16px;
            border: none;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
        }
        
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 16px 16px 0 0;
            border: none;
        }
        
        .form-control, .form-select {
            border-radius: 8px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            padding: 12px 16px;
            transition: all 0.3s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
    </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-coins';
                $admin_page_actions = '<span class="badge rounded-pill admin-badge-soft me-2">' . count($packages) . ' پکیج</span>'
                    . '<button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addPackageModal"><i class="fas fa-plus ms-1"></i>افزودن پکیج جدید</button>';
                include 'includes/topbar.php';
                ?>

                    <!-- Messages -->
                    <?php if (isset($_GET['success'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php
                            switch ($_GET['success']) {
                                case 'added': echo 'پکیج با موفقیت اضافه شد!'; break;
                                case 'updated': echo 'پکیج با موفقیت ویرایش شد!'; break;
                                case 'deleted': echo 'پکیج با موفقیت حذف شد!'; break;
                            }
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <div class="table-container">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>شناسه</th>
                                        <th>نام</th>
                                        <th>تعداد سکه</th>
                                        <th>قیمت</th>
                                        <th>قیمت اصلی</th>
                                        <th>تخفیف</th>
                                        <th>اولویت</th>
                                        <th>Product ID</th>
                                        <th>محبوب</th>
                                        <th>پیشنهاد ویژه</th>
                                        <th>وضعیت</th>
                                        <th>عملیات</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($packages as $package): ?>
                                    <tr>
                                        <td><?php echo $package['id']; ?></td>
                                        <td><?php echo htmlspecialchars($package['name']); ?></td>
                                        <td>
                                            <span class="badge bg-primary">
                                                <i class="fas fa-coins me-1"></i><?php echo $package['coins']; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-success">
                                                <i class="fas fa-dollar-sign me-1"></i><?php echo $package['price']; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="text-muted">
                                                <i class="fas fa-dollar-sign me-1"></i><?php echo $package['original_price']; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($package['discount'] > 0): ?>
                                                <span class="badge bg-warning">
                                                    <i class="fas fa-percentage me-1"></i><?php echo $package['discount']; ?>% تخفیف
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted">بدون تخفیف</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge bg-secondary">
                                                <i class="fas fa-sort-numeric-up me-1"></i><?php echo $package['priority']; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if (!empty($package['product_id'])): ?>
                                                <code class="text-primary"><?php echo htmlspecialchars($package['product_id']); ?></code>
                                            <?php else: ?>
                                                <span class="text-muted">تعریف نشده</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($package['is_popular']): ?>
                                                <span class="badge bg-danger">
                                                    <i class="fas fa-star me-1"></i>محبوب
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted">عادی</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($package['is_special_offer']): ?>
                                                <?php 
                                                $isExpired = false;
                                                if ($package['special_offer_end_time']) {
                                                    $endTime = new DateTime($package['special_offer_end_time']);
                                                    $isExpired = $endTime < $currentTime;
                                                }
                                                ?>
                                                <?php if ($isExpired): ?>
                                                    <span class="badge bg-secondary">
                                                        <i class="fas fa-clock me-1"></i>منقضی شده
                                                    </span>
                                                    <br><small class="text-muted">تا: <?php echo date('Y/m/d H:i', strtotime($package['special_offer_end_time'])); ?></small>
                                                <?php else: ?>
                                                    <span class="badge bg-warning">
                                                        <i class="fas fa-fire me-1"></i>پیشنهاد ویژه
                                                    </span>
                                                    <br><small class="text-muted">تا: <?php echo date('Y/m/d H:i', strtotime($package['special_offer_end_time'])); ?></small>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <span class="text-muted">عادی</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($package['is_active']): ?>
                                                <span class="badge bg-success">
                                                    <i class="fas fa-check me-1"></i>فعال
                                                </span>
                                            <?php else: ?>
                                                <span class="badge bg-danger">
                                                    <i class="fas fa-times me-1"></i>غیرفعال
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary btn-action" onclick="editPackage(<?php echo htmlspecialchars(json_encode($package)); ?>)">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger btn-action" onclick="deletePackage(<?php echo $package['id']; ?>)">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
        </div>
    </main>
    
    <!-- Add Package Modal -->
    <div class="modal fade" id="addPackageModal" 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">
                    <input type="hidden" name="action" value="add">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">نام پکیج</label>
                            <input type="text" class="form-control" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">تعداد سکه</label>
                            <input type="number" class="form-control" name="coins" min="1" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">قیمت ($)</label>
                            <input type="number" class="form-control" name="price" min="0" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">قیمت اصلی ($)</label>
                            <input type="number" class="form-control" name="original_price" min="0" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">تخفیف (%)</label>
                            <input type="number" class="form-control" name="discount" min="0" max="100" value="0">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">اولویت</label>
                            <input type="number" class="form-control" name="priority" min="0" value="0">
                            <small class="text-muted">پکیج‌های با اولویت بالاتر ابتدا نمایش داده می‌شوند</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Product ID (Google Play)</label>
                            <input type="text" class="form-control" name="product_id" placeholder="coin_package_100">
                            <small class="text-muted">شناسه محصول در Google Play Console (اختیاری)</small>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_popular" id="isPopular">
                                <label class="form-check-label" for="isPopular">
                                    علامت‌گذاری به عنوان محبوب
                                </label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_special_offer" id="isSpecialOffer">
                                <label class="form-check-label" for="isSpecialOffer">
                                    پیشنهاد ویژه
                                </label>
                            </div>
                        </div>
                        <div class="mb-3" id="specialOfferFields" style="display: none;">
                            <label class="form-label">زمان پایان پیشنهاد ویژه</label>
                            <input type="datetime-local" class="form-control" name="special_offer_end_time" id="specialOfferEndTime">
                            <small class="text-muted">زمان پایان پیشنهاد ویژه را مشخص کنید</small>
                        </div>
                        <div class="mb-3" id="specialOfferColorField" style="display: none;">
                            <label class="form-label">رنگ پس‌زمینه پیشنهاد ویژه</label>
                            <input type="color" class="form-control" name="special_offer_bg_color" id="specialOfferBgColor" value="#FF6B6B">
                            <small class="text-muted">رنگ پس‌زمینه کارت پیشنهاد ویژه</small>
                        </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 Package Modal -->
    <div class="modal fade" id="editPackageModal" 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">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">نام پکیج</label>
                            <input type="text" class="form-control" name="name" id="edit_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">تعداد سکه</label>
                            <input type="number" class="form-control" name="coins" id="edit_coins" min="1" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">قیمت ($)</label>
                            <input type="number" class="form-control" name="price" id="edit_price" min="0" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">قیمت اصلی ($)</label>
                            <input type="number" class="form-control" name="original_price" id="edit_original_price" min="0" step="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">تخفیف (%)</label>
                            <input type="number" class="form-control" name="discount" id="edit_discount" min="0" max="100">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">اولویت</label>
                            <input type="number" class="form-control" name="priority" id="edit_priority" min="0">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Product ID (Google Play)</label>
                            <input type="text" class="form-control" name="product_id" id="edit_product_id" placeholder="coin_package_100">
                            <small class="text-muted">شناسه محصول در Google Play Console (اختیاری)</small>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_popular" id="edit_is_popular">
                                <label class="form-check-label" for="edit_is_popular">
                                    علامت‌گذاری به عنوان محبوب
                                </label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_special_offer" id="edit_is_special_offer">
                                <label class="form-check-label" for="edit_is_special_offer">
                                    پیشنهاد ویژه
                                </label>
                            </div>
                        </div>
                        <div class="mb-3" id="editSpecialOfferFields" style="display: none;">
                            <label class="form-label">زمان پایان پیشنهاد ویژه</label>
                            <input type="datetime-local" class="form-control" name="special_offer_end_time" id="edit_special_offer_end_time">
                            <small class="text-muted">زمان پایان پیشنهاد ویژه را مشخص کنید</small>
                        </div>
                        <div class="mb-3" id="editSpecialOfferColorField" style="display: none;">
                            <label class="form-label">رنگ پس‌زمینه پیشنهاد ویژه</label>
                            <input type="color" class="form-control" name="special_offer_bg_color" id="edit_special_offer_bg_color" value="#FF6B6B">
                            <small class="text-muted">رنگ پس‌زمینه کارت پیشنهاد ویژه</small>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_active" id="edit_is_active">
                                <label class="form-check-label" for="edit_is_active">
                                    فعال
                                </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>
    
    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deletePackageModal" 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>
                <div class="modal-body">
                    <p>آیا مطمئن هستید که می‌خواهید این پکیج را حذف کنید؟ این عملیات قابل بازگشت نیست.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                    <form method="POST" style="display: inline;">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" id="delete_id">
                        <button type="submit" class="btn btn-danger">حذف</button>
                    </form>
                </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>
        // Toggle special offer fields visibility
        document.getElementById('isSpecialOffer').addEventListener('change', function() {
            const fields = document.getElementById('specialOfferFields');
            const colorField = document.getElementById('specialOfferColorField');
            if (this.checked) {
                fields.style.display = 'block';
                colorField.style.display = 'block';
            } else {
                fields.style.display = 'none';
                colorField.style.display = 'none';
            }
        });
        
        document.getElementById('edit_is_special_offer').addEventListener('change', function() {
            const fields = document.getElementById('editSpecialOfferFields');
            const colorField = document.getElementById('editSpecialOfferColorField');
            if (this.checked) {
                fields.style.display = 'block';
                colorField.style.display = 'block';
            } else {
                fields.style.display = 'none';
                colorField.style.display = 'none';
            }
        });
        
        function editPackage(package) {
            document.getElementById('edit_id').value = package.id;
            document.getElementById('edit_name').value = package.name;
            document.getElementById('edit_coins').value = package.coins;
            document.getElementById('edit_price').value = package.price;
            document.getElementById('edit_original_price').value = package.original_price;
            document.getElementById('edit_discount').value = package.discount;
            document.getElementById('edit_priority').value = package.priority;
            document.getElementById('edit_product_id').value = package.product_id || '';
            document.getElementById('edit_is_popular').checked = package.is_popular == 1;
            document.getElementById('edit_is_special_offer').checked = package.is_special_offer == 1;
            document.getElementById('edit_is_active').checked = package.is_active == 1;
            
            // Handle special offer fields
            if (package.is_special_offer == 1) {
                document.getElementById('editSpecialOfferFields').style.display = 'block';
                document.getElementById('editSpecialOfferColorField').style.display = 'block';
                if (package.special_offer_end_time) {
                    document.getElementById('edit_special_offer_end_time').value = package.special_offer_end_time.replace(' ', 'T');
                }
                if (package.special_offer_bg_color) {
                    document.getElementById('edit_special_offer_bg_color').value = package.special_offer_bg_color;
                }
            } else {
                document.getElementById('editSpecialOfferFields').style.display = 'none';
                document.getElementById('editSpecialOfferColorField').style.display = 'none';
            }
            
            new bootstrap.Modal(document.getElementById('editPackageModal')).show();
        }
        
        function deletePackage(id) {
            document.getElementById('delete_id').value = id;
            new bootstrap.Modal(document.getElementById('deletePackageModal')).show();
        }
        
        // Auto-refresh page every 30 seconds to check for expired special offers
        setInterval(function() {
            location.reload();
        }, 30000); // 30 seconds
    </script>
</body>
</html>
