<?php
// modules/festivals.php
require_once '../includes/auth.php';
checkLogin();
require_once '../config/db.php';
require_once '../includes/functions.php';

if (!isAdmin()) {
    header("Location: dashboard.php");
    exit;
}

$msg = '';
$error = '';

try {
    $pdo->exec("ALTER TABLE plans ADD COLUMN IF NOT EXISTS has_timer TINYINT(1) DEFAULT 0");
    $pdo->exec("ALTER TABLE plans ADD COLUMN IF NOT EXISTS timer_end DATETIME NULL");
} catch (PDOException $e) {}

if (!function_exists('jalali_to_gregorian')) {
    function jalali_to_gregorian($jy, $jm, $jd, $mod = '') {
        $jy += 1595;
        $days = -355668 + (365 * $jy) + ((int)($jy / 33) * 8) + ((int)((($jy % 33) + 3) / 4)) + $jd + (($jm < 7) ? ($jm - 1) * 31 : (($jm - 7) * 30) + 186);
        $gy = 400 * ((int)($days / 146097));
        $days %= 146097;
        if ($days > 36524) {
            $gy += 100 * ((int)(--$days / 36524));
            $days %= 36524;
            if ($days >= 365) $days++;
        }
        $gy += 4 * ((int)($days / 1461));
        $days %= 1461;
        if ($days > 365) {
            $gy += (int)(($days - 1) / 365);
            $days = ($days - 1) % 365;
        }
        $gd = $days + 1;
        $sal_a = array(0, 31, (($gy % 4 == 0 && $gy % 100 != 0) || ($gy % 400 == 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
        for ($gm = 0; $gm < 13 && $gd > $sal_a[$gm]; $gm++) $gd -= $sal_a[$gm];
        return ($mod == '') ? array($gy, $gm, $gd) : $gy . $mod . sprintf("%02d", $gm) . $mod . sprintf("%02d", $gd);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    // مدیریت تایمر برای طرح‌های فروشگاه
    if ($_POST['action'] === 'update_plan_timer') {
        $planId = (int)$_POST['plan_id'];
        $shamsiDateInput = trim($_POST['plan_target_date_shamsi']); 
        $timeInput = trim($_POST['plan_target_time']); 
        $isActive = isset($_POST['plan_has_timer']) ? 1 : 0;

        if ($isActive) {
            $dateParts = explode('/', $shamsiDateInput);
            if (count($dateParts) == 3) {
                $gregorianDate = jalali_to_gregorian((int)$dateParts[0], (int)$dateParts[1], (int)$dateParts[2], '-');
                $formattedDateTime = $gregorianDate . ' ' . $timeInput . ':00';
                
                $pdo->prepare("UPDATE plans SET has_timer = 1, timer_end = ? WHERE id = ?")->execute([$formattedDateTime, $planId]);
                $msg = "تایمر برای طرح فروشگاهی مورد نظر فعال شد.";
            } else {
                $error = "فرمت تاریخ شمسی نامعتبر است.";
            }
        } else {
            $pdo->prepare("UPDATE plans SET has_timer = 0, timer_end = NULL WHERE id = ?")->execute([$planId]);
            $msg = "تایمر از روی طرح برداشته شد (همیشه در فروشگاه قابل رویت است).";
        }
    }
}

$plans = $pdo->query("SELECT id, plan_name, has_timer, timer_end FROM plans ORDER BY id ASC")->fetchAll();

require_once '../includes/header.php';
?>

<div class="mb-6 flex justify-between items-end">
    <div>
        <h1 class="text-2xl font-black text-gray-800 dark:text-white tracking-tight">جشنواره‌های فروش</h1>
        <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">مدیریت تایمرهای زمان‌دار برای محصولات فروشگاه</p>
    </div>
</div>

<?php if($msg): ?><div class="bg-green-100 dark:bg-emerald-900/30 border border-green-400 dark:border-emerald-800 text-green-700 dark:text-emerald-400 px-4 py-3 rounded-xl mb-6 font-bold shadow-sm">✅ <?php echo $msg; ?></div><?php endif; ?>
<?php if($error): ?><div class="bg-red-100 dark:bg-rose-900/30 border border-red-400 dark:border-rose-800 text-red-700 dark:text-rose-400 px-4 py-3 rounded-xl mb-6 font-bold shadow-sm">❌ <?php echo $error; ?></div><?php endif; ?>

<div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 overflow-hidden border-t-8 border-t-blue-500 mb-8">
    <div class="p-6 border-b border-gray-100 dark:border-slate-700 bg-gray-50 dark:bg-slate-800/80">
        <h2 class="text-lg font-black text-gray-800 dark:text-white flex items-center gap-2">
            <span class="text-xl">🛒</span> مدیریت جشنواره‌های فروشگاهی
        </h2>
        <p class="text-xs text-gray-500 dark:text-gray-400 mt-2 font-bold">
            برای هر طرح می‌توانید زمان پایان مشخص کنید. پس از این زمان، طرح از فروشگاه مخفی شده و قابل خرید نیست.
        </p>
    </div>
    
    <div class="overflow-x-auto p-4">
        <table class="w-full text-sm text-right text-gray-600 dark:text-gray-400">
            <thead class="bg-gray-100 dark:bg-slate-700/50 text-gray-700 dark:text-gray-300">
                <tr>
                    <th class="px-4 py-3 rounded-tr-xl">نام طرح فروش</th>
                    <th class="px-4 py-3 text-center">وضعیت تایمر</th>
                    <th class="px-4 py-3">زمان پایان فروش (شمارش معکوس)</th>
                    <th class="px-4 py-3 text-center rounded-tl-xl">تنظیمات</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100 dark:divide-slate-700">
                <?php foreach($plans as $p): 
                    $isExpired = false;
                    $shamsiEnd = '-';
                    if ($p['has_timer'] && !empty($p['timer_end'])) {
                        $dt = new DateTime($p['timer_end']);
                        $shamsiEnd = sprintf("%04d/%02d/%02d", ...gregorian_to_jalali($dt->format('Y'), $dt->format('m'), $dt->format('d'))) . ' ' . $dt->format('H:i');
                        if (time() > strtotime($p['timer_end'])) {
                            $isExpired = true;
                        }
                    }
                ?>
                    <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/30 transition">
                        <td class="px-4 py-4 font-black text-gray-800 dark:text-gray-200">
                            <?php echo htmlspecialchars($p['plan_name']); ?>
                        </td>
                        <td class="px-4 py-4 text-center">
                            <?php if($p['has_timer']): ?>
                                <?php if($isExpired): ?>
                                    <span class="bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400 px-2 py-1 rounded-lg text-xs font-bold border border-rose-200 dark:border-rose-800">پایان یافته (مخفی)</span>
                                <?php else: ?>
                                    <span class="bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 px-2 py-1 rounded-lg text-xs font-bold border border-emerald-200 dark:border-emerald-800">فعال (زمان‌دار)</span>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="bg-gray-100 text-gray-500 dark:bg-slate-700 dark:text-gray-400 px-2 py-1 rounded-lg text-xs font-bold border border-gray-200 dark:border-slate-600">نامحدود (دائم)</span>
                            <?php endif; ?>
                        </td>
                        <td class="px-4 py-4 font-mono font-bold <?php echo $isExpired ? 'text-rose-500 line-through' : 'text-blue-600 dark:text-blue-400'; ?>" dir="ltr">
                            <?php echo $shamsiEnd; ?>
                        </td>
                        <td class="px-4 py-4 text-center">
                            <button type="button" onclick="openPlanTimerModal(<?php echo $p['id']; ?>, '<?php echo htmlspecialchars($p['plan_name'], ENT_QUOTES); ?>', <?php echo $p['has_timer']; ?>, '<?php echo $p['has_timer'] && !empty($p['timer_end']) ? date('Y-m-d H:i', strtotime($p['timer_end'])) : ''; ?>')" class="text-blue-500 hover:text-blue-700 bg-blue-50 dark:bg-blue-900/30 px-3 py-1.5 rounded-lg transition font-bold text-xs">
                                تنظیم تایمر ⚙️
                            </button>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- مودال تنظیمات تایمر اختصاصی طرح -->
<div id="planTimerModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm hidden items-center justify-center z-50 px-4 transition-opacity opacity-0">
    <div class="bg-white dark:bg-slate-800 rounded-3xl shadow-2xl w-full max-w-lg overflow-hidden transform scale-95 transition-transform border border-gray-100 dark:border-slate-700" id="planTimerModalContent">
        <div class="bg-blue-50 dark:bg-blue-900/30 px-6 py-4 border-b border-blue-100 dark:border-blue-800 flex justify-between items-center">
            <h3 class="font-black text-blue-800 dark:text-blue-300" id="modalPlanName">تایمر طرح</h3>
            <button type="button" onclick="closePlanTimerModal()" class="text-blue-400 hover:text-rose-500 text-2xl transition">&times;</button>
        </div>
        <form method="POST" class="p-6 space-y-4">
            <input type="hidden" name="action" value="update_plan_timer">
            <input type="hidden" name="plan_id" id="edit_plan_id">
            
            <div class="flex items-center gap-3 bg-gray-50 dark:bg-slate-700/50 p-4 rounded-xl border border-gray-200 dark:border-slate-600 mb-4">
                <input type="checkbox" name="plan_has_timer" id="plan_has_timer" value="1" class="w-5 h-5 text-blue-600 rounded focus:ring-blue-500 cursor-pointer" onchange="toggleDateInputs(this.checked)">
                <label for="plan_has_timer" class="font-bold text-sm text-gray-800 dark:text-gray-200 cursor-pointer select-none text-rose-500">فعال‌سازی فروش زمان‌دار (جشنواره)</label>
            </div>
            
            <div id="dateInputsContainer" class="grid grid-cols-2 gap-4 transition-opacity opacity-50 pointer-events-none">
                <div>
                    <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">تاریخ پایان (شمسی)</label>
                    <input type="text" name="plan_target_date_shamsi" id="plan_date_input" placeholder="مثال: 1403/12/29" class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl focus:border-blue-500 outline-none font-mono font-bold bg-white dark:bg-slate-700 dark:text-white text-sm" dir="ltr">
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">ساعت پایان</label>
                    <input type="time" name="plan_target_time" id="plan_time_input" class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl focus:border-blue-500 outline-none font-mono font-bold bg-white dark:bg-slate-700 dark:text-white text-sm" dir="ltr">
                </div>
            </div>

            <p class="text-[11px] text-gray-400 font-bold mb-4">در صورتی که تیک فعال‌سازی برداشته شود، این طرح همیشه در فروشگاه در دسترس خواهد بود.</p>

            <div class="pt-2 flex gap-3">
                <button type="submit" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 rounded-xl shadow-md transition">ذخیره تایمر</button>
                <button type="button" onclick="closePlanTimerModal()" class="flex-1 bg-gray-100 dark:bg-slate-700 hover:bg-gray-200 dark:hover:bg-slate-600 text-gray-700 dark:text-gray-300 font-bold py-3 rounded-xl transition">انصراف</button>
            </div>
        </form>
    </div>
</div>

<script>
function gregorianToJalali(gy, gm, gd) {
    var g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
    var gy2 = (gm > 2) ? (gy + 1) : gy;
    var days = 355666 + (365 * gy) + parseInt((gy2 + 3) / 4) - parseInt((gy2 + 99) / 100) + parseInt((gy2 + 399) / 400) + gd + g_d_m[gm - 1];
    var jy = -1595 + (33 * parseInt(days / 12053));
    days %= 12053;
    jy += 4 * parseInt(days / 1461);
    days %= 1461;
    if (days > 365) {
        jy += parseInt((days - 1) / 365);
        days = (days - 1) % 365;
    }
    var jm, jd;
    if (days < 186) {
        jm = 1 + parseInt(days / 31);
        jd = 1 + (days % 31);
    } else {
        jm = 7 + parseInt((days - 186) / 30);
        jd = 1 + ((days - 186) % 30);
    }
    return [jy, jm, jd];
}

function padZero(num) { return num < 10 ? '0' + num : num; }

const modal = document.getElementById('planTimerModal');
const modalContent = document.getElementById('planTimerModalContent');
const container = document.getElementById('dateInputsContainer');

function toggleDateInputs(isActive) {
    if (isActive) {
        container.classList.remove('opacity-50', 'pointer-events-none');
        document.getElementById('plan_date_input').required = true;
        document.getElementById('plan_time_input').required = true;
    } else {
        container.classList.add('opacity-50', 'pointer-events-none');
        document.getElementById('plan_date_input').required = false;
        document.getElementById('plan_time_input').required = false;
    }
}

function openPlanTimerModal(id, name, hasTimer, dbDateStr) {
    document.getElementById('edit_plan_id').value = id;
    document.getElementById('modalPlanName').innerText = "تایمر فروش: " + name;
    
    document.getElementById('plan_has_timer').checked = (hasTimer == 1);
    toggleDateInputs(hasTimer == 1);
    
    if (hasTimer == 1 && dbDateStr) {
        let parts = dbDateStr.split(' ');
        let dateParts = parts[0].split('-');
        let timePart = parts[1];
        
        let jalali = gregorianToJalali(parseInt(dateParts[0]), parseInt(dateParts[1]), parseInt(dateParts[2]));
        document.getElementById('plan_date_input').value = jalali[0] + '/' + padZero(jalali[1]) + '/' + padZero(jalali[2]);
        document.getElementById('plan_time_input').value = timePart;
    } else {
        document.getElementById('plan_date_input').value = '';
        document.getElementById('plan_time_input').value = '';
    }
    
    modal.classList.remove('hidden');
    modal.classList.add('flex');
    setTimeout(() => {
        modal.classList.remove('opacity-0');
        modalContent.classList.remove('scale-95');
    }, 10);
}

function closePlanTimerModal() {
    modal.classList.add('opacity-0');
    modalContent.classList.add('scale-95');
    setTimeout(() => {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }, 300);
}

modal.addEventListener('click', function(e) {
    if (e.target === modal) closePlanTimerModal();
});
</script>

<?php require_once '../includes/footer.php'; ?>