<?php
/**
 * generate_share.php - Modul Broadcast & Tugas AI
 * Developer: Sikawarsito, S.Kom
 * Fitur: Upload File, Limitasi Akun, Penguncian Fitur FREE (SaaS Monetization).
 */
session_start();
include 'config/database.php';

// Proteksi Login
if (!isset($_SESSION['user_id'])) {
    die("Akses ditolak. Silakan login terlebih dahulu.");
}

$user_id = $_SESSION['user_id'];

// --- [PROTEKSI AKSES BROADCAST & AMBIL STATUS AKUN] ---
$stmt_cek_akses = $conn->prepare("SELECT role, status_broadcast, status_akun FROM users WHERE id = ?");
$stmt_cek_akses->bind_param("i", $user_id);
$stmt_cek_akses->execute();
$res_akses = $stmt_cek_akses->get_result();
$user_data = $res_akses->fetch_assoc();
$stmt_cek_akses->close();

if ($user_data['role'] !== 'admin' && $user_data['status_broadcast'] !== 'approved') {
    die("<div style='font-family: sans-serif; text-align: center; margin-top: 50px;'>
            <h2 style='color: red;'>Akses Ditolak</h2>
            <p>Maaf, Anda tidak memiliki izin atau fitur ini sedang diblokir oleh Admin.</p>
            <a href='index.php'>Kembali ke Dashboard</a>
         </div>");
}

$status_akun = $user_data['status_akun'] ?? 'free';
// VARIABEL SAKTI UNTUK MENGECEK STATUS PREMIUM
$is_pro = ($status_akun === 'pro' || $user_data['role'] === 'admin');

// --- [PENGATURAN PAKET BISNIS] ---
if ($is_pro) {
    $limit_tugas = 10;
    $masa_aktif_hari = 7; // 1 Minggu
    $nama_paket = "PRO / ADMIN";
    $badge_color = "bg-success";
} else {
    $limit_tugas = 3;
    $masa_aktif_hari = 3; // 3 Hari
    $nama_paket = "FREE";
    $badge_color = "bg-secondary";
}

// --- [AUTO-CLEANUP: Hapus Tugas Kedaluwarsa Otomatis] ---
$stmt_clean = $conn->prepare("DELETE FROM share_tugas WHERE user_id = ? AND created_at < DATE_SUB(NOW(), INTERVAL ? DAY)");
$stmt_clean->bind_param("ii", $user_id, $masa_aktif_hari);
$stmt_clean->execute();
$stmt_clean->close();
// --------------------------------------------------------

$pesan_notif = "";

// --- HANDLER FORM (TAMBAH TUGAS) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'tambah') {
    $prompt = trim(strtolower($_POST['trigger_prompt']));
    $deskripsi = trim($_POST['deskripsi_tugas']);
    $format = $_POST['format_tugas'] ?? 'text';
    
    // 1. LOGIKA DROPDOWN FORMAT KODING
    if ($format !== 'text') {
        $deskripsi = "Berikut adalah koding materi/tugas:\n\n```" . $format . "\n" . $deskripsi . "\n```";
    }

    // 2. CEK LIMIT TUGAS
    $stmt_limit = $conn->prepare("SELECT COUNT(id) as total_tugas FROM share_tugas WHERE user_id = ?");
    $stmt_limit->bind_param("i", $user_id);
    $stmt_limit->execute();
    $data_limit = $stmt_limit->get_result()->fetch_assoc();
    $stmt_limit->close();

    if ($data_limit['total_tugas'] >= $limit_tugas) {
        $upsell_text = (!$is_pro) ? "<hr class='my-2'><a href='upgrade_pro.php' class='alert-link fw-bold' style='color: #b45309;'>🚀 Upgrade ke PRO untuk limit 10 Tugas / Minggu!</a>" : "";
        
        $pesan_notif = "
            <div class='alert alert-warning shadow-sm border-0 rounded-4 mb-4' style='background-color: #fffbeb; border-left: 5px solid #f59e0b !important;'>
                <div class='d-flex align-items-center'>
                    <i class='bi bi-hdd-network fs-2 me-3' style='color: #f59e0b;'></i> 
                    <div>
                        <h6 class='mb-1 fw-bold' style='color: #b45309;'>Penyimpanan Penuh (Paket $nama_paket)</h6>
                        <p class='mb-0 small text-muted'>Anda telah mencapai batas maksimal <b>$limit_tugas tugas aktif</b>. Karena akun Anda FREE, tugas tidak dapat dihapus manual dan akan hilang otomatis setelah 3 hari.</p>
                        $upsell_text
                    </div>
                </div>
            </div>";
    } else {
        // 3. LOGIKA UPLOAD LAMPIRAN (DIBLOKIR UNTUK FREE)
        $lampiran_markdown = "";
        if (isset($_FILES['file_tugas']) && $_FILES['file_tugas']['error'] === UPLOAD_ERR_OK) {
            if ($is_pro) {
                // HANYA PRO YANG BISA UPLOAD FILE
                $file_name = preg_replace("/[^a-zA-Z0-9.-]/", "_", basename($_FILES['file_tugas']['name']));
                $file_size = $_FILES['file_tugas']['size'];
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                $allowed_exts = ['zip', 'jpg', 'jpeg', 'png', 'pdf', 'docx', 'xlsx', 'pptx', 'html', 'php', 'ino', 'css', 'js'];
                
                if (in_array($file_ext, $allowed_exts) && $file_size <= 5242880) { // Maks 5MB
                    $upload_dir = 'uploads/tugas/';
                    if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
                    $new_filename = time() . '_' . $file_name;
                    $destination = $upload_dir . $new_filename;
                    
                    if (move_uploaded_file($_FILES['file_tugas']['tmp_name'], $destination)) {
                        if (in_array($file_ext, ['jpg', 'jpeg', 'png'])) {
                            $lampiran_markdown = "\n\n<br> **📷 Lampiran Gambar:**\n![$file_name]($destination)";
                        } else {
                            $lampiran_markdown = "\n\n<br> **📦 Lampiran File:**\n[⬇️ Download File $file_name]($destination)";
                        }
                    }
                } else {
                    $pesan_notif = "<div class='alert alert-warning'>Peringatan: Lampiran gagal diunggah karena format tidak didukung atau melebihi 5MB.</div>";
                }
            } else {
                // AKUN FREE TERCEGAT DI SINI
                $pesan_notif = "<div class='alert alert-danger shadow-sm border-0 mb-4'><i class='bi bi-lock-fill me-2'></i><b>Akses Ditolak:</b> Fitur Upload File hanya tersedia untuk pengguna <b>Paket PRO</b>. Tugas Anda tetap disimpan tanpa lampiran.</div>";
            }
        }

        $deskripsi .= $lampiran_markdown;
        
        // 4. SIMPAN KE DATABASE
        if (!empty($prompt) && !empty($deskripsi)) {
            $stmt_cek = $conn->prepare("SELECT id FROM share_tugas WHERE trigger_prompt = ?");
            $stmt_cek->bind_param("s", $prompt);
            $stmt_cek->execute();
            
            if ($stmt_cek->get_result()->num_rows > 0) {
                $pesan_notif = "
                    <div class='alert alert-danger shadow-sm border-0 rounded-4 mb-4' style='background-color: #fef2f2; border-left: 5px solid #ef4444 !important;'>
                        <div class='d-flex align-items-center'>
                            <i class='bi bi-shield-exclamation fs-2 me-3' style='color: #ef4444;'></i> 
                            <div>
                                <h6 class='mb-1 fw-bold' style='color: #991b1b;'>Gagal: Prompt Sudah Terpakai</h6>
                                <p class='mb-0 small text-muted'>Kata kunci pemicu <b>\"$prompt\"</b> sudah digunakan. Mohon gunakan kombinasi kata yang berbeda.</p>
                            </div>
                        </div>
                    </div>";
            } else {
                $stmt_insert = $conn->prepare("INSERT INTO share_tugas (user_id, trigger_prompt, deskripsi_tugas) VALUES (?, ?, ?)");
                $stmt_insert->bind_param("iss", $user_id, $prompt, $deskripsi);
                if ($stmt_insert->execute()) {
                    
                    if (!$is_pro) {
                        $upsell_msg = "<hr class='my-2 border-success opacity-25'><p class='mb-0 small' style='color: #065f46;'><b>Info Paket FREE:</b> Tugas ini akan aktif selama <b>3 Hari</b> dan <b>tidak bisa dihapus secara manual</b>. <a href='upgrade_pro.php' class='fw-bold text-success text-decoration-underline'>Tingkatkan ke PRO</a> untuk kontrol penuh!</p>";
                    } else {
                        $upsell_msg = "<hr class='my-2 border-success opacity-25'><p class='mb-0 small' style='color: #065f46;'><b>Member PRO:</b> Tugas ini akan aktif selama <b>7 Hari (1 Minggu)</b> sebelum terhapus otomatis.</p>";
                    }

                    if(empty($pesan_notif) || strpos($pesan_notif, 'Akses Ditolak') !== false) {
                        // Jika ada pesan notif blokir upload, biarkan muncul di atas, lalu tambah alert sukses
                        $pesan_notif .= "
                        <div class='alert alert-success shadow-sm border-0 rounded-4 mb-4' style='background-color: #f0fdf4; border-left: 5px solid #10b981 !important;'>
                            <div class='d-flex align-items-start'>
                                <i class='bi bi-check-circle-fill fs-3 me-3 mt-1' style='color: #10b981;'></i> 
                                <div>
                                    <h6 class='mb-1 fw-bold' style='color: #065f46;'>Tugas Berhasil Didaftarkan!</h6>
                                    <p class='mb-0 small text-muted'>Siswa Anda sudah bisa mengakses materi/tugas ini. (Sisa Kuota: <b>" . ($limit_tugas - $data_limit['total_tugas'] - 1) . " Tugas</b>).</p>
                                    $upsell_msg
                                </div>
                            </div>
                        </div>";
                    }
                } else {
                    $pesan_notif = "<div class='alert alert-danger'>Gagal menyimpan tugas ke database.</div>";
                }
                $stmt_insert->close();
            }
            $stmt_cek->close();
        }
    }
}

// --- HANDLER HAPUS TUGAS (DIBLOKIR UNTUK FREE) ---
if (isset($_GET['hapus'])) {
    if ($is_pro) {
        $id_hapus = (int)$_GET['hapus'];
        $stmt_hapus = $conn->prepare("DELETE FROM share_tugas WHERE id = ? AND user_id = ?");
        $stmt_hapus->bind_param("ii", $id_hapus, $user_id);
        if ($stmt_hapus->execute()) {
            $pesan_notif = "
            <div class='alert alert-success shadow-sm border-0 rounded-4 mb-4' style='background-color: #f0fdf4; border-left: 5px solid #10b981 !important;'>
                <div class='d-flex align-items-center'>
                    <i class='bi bi-trash-fill fs-3 me-3' style='color: #10b981;'></i> 
                    <div>
                        <h6 class='mb-1 fw-bold' style='color: #065f46;'>Dihapus!</h6>
                        <p class='mb-0 small text-muted'>Tugas berhasil dihapus dari sistem.</p>
                    </div>
                </div>
            </div>";
        }
        $stmt_hapus->close();
    } else {
        // AKUN FREE MENCOBA HAPUS VIA URL
        $pesan_notif = "
        <div class='alert alert-danger shadow-sm border-0 rounded-4 mb-4' style='background-color: #fef2f2; border-left: 5px solid #ef4444 !important;'>
            <div class='d-flex align-items-center'>
                <i class='bi bi-lock-fill fs-3 me-3' style='color: #ef4444;'></i> 
                <div>
                    <h6 class='mb-1 fw-bold' style='color: #991b1b;'>Akses Ditolak (Khusus PRO)</h6>
                    <p class='mb-0 small text-muted'>Akun FREE tidak memiliki izin untuk menghapus tugas secara manual. Tugas Anda akan terhapus otomatis dalam 3 hari.</p>
                </div>
            </div>
        </div>";
    }
}

// --- AMBIL DATA TUGAS MILIK USER INI ---
$data_tugas = [];
$stmt_get = $conn->prepare("SELECT * FROM share_tugas WHERE user_id = ? ORDER BY id DESC");
$stmt_get->bind_param("i", $user_id);
$stmt_get->execute();
$res = $stmt_get->get_result();
while ($row = $res->fetch_assoc()) {
    $data_tugas[] = $row;
}
$stmt_get->close();

$total_tugas_sekarang = count($data_tugas);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Tugas & Broadcast AI</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        body { font-family: 'Inter', sans-serif; background-color: #f8fafc; color: #1e293b; }
        .card { border: none; border-radius: 12px; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); }
        .bg-gradient-primary { background: linear-gradient(90deg, #4285f4, #9b72cb); color: white; }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="fw-bold mb-1"><i class="bi bi-broadcast me-2 text-primary"></i> Kelola Broadcast Tugas</h3>
            <span class="badge <?= $badge_color ?> fw-bold rounded-pill px-3 py-2">
                <i class="bi bi-person-badge me-1"></i> AKUN <?= $nama_paket ?> 
                (<?= $total_tugas_sekarang ?>/<?= $limit_tugas ?> Tugas)
            </span>
        </div>
        <a href="index.php" class="btn btn-outline-secondary rounded-pill fw-bold"><i class="bi bi-arrow-left"></i> Kembali ke AI</a>
    </div>

    <?= $pesan_notif ?>

    <div class="row">
        <!-- FORM INPUT TUGAS -->
        <div class="col-md-4 mb-4">
            <div class="card h-100">
                <div class="card-header bg-gradient-primary fw-bold border-0" style="border-radius: 12px 12px 0 0;">
                    <i class="bi bi-plus-circle"></i> Buat Tugas Baru
                </div>
                <div class="card-body">
                    <form method="POST" action="" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="tambah">
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold small text-muted">Prompt Pemicu (Trigger)</label>
                            <input type="text" class="form-control" name="trigger_prompt" placeholder="Contoh: materi dari sika" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold small text-muted">Format Tampilan</label>
                            <select class="form-select" name="format_tugas">
                                <option value="text">Teks Biasa / Narasi</option>
                                <option value="html">Koding HTML</option>
                                <option value="php">Koding PHP</option>
                                <option value="javascript">Koding JavaScript</option>
                                <option value="cpp">Koding Arduino / C++</option>
                                <option value="sql">Koding SQL</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold small text-muted">Isi Tugas / Pesan</label>
                            <textarea class="form-control" name="deskripsi_tugas" rows="5" placeholder="Ketik narasi atau paste koding di sini..." required></textarea>
                        </div>

                        <!-- UI UPLOAD FILE: DINAMIS BERDASARKAN STATUS AKUN -->
                        <?php if($is_pro): ?>
                            <div class="mb-4 p-3 bg-light rounded border border-dashed">
                                <label class="form-label fw-bold small text-muted"><i class="bi bi-paperclip"></i> Lampirkan File (Opsional)</label>
                                <input class="form-control form-control-sm" type="file" name="file_tugas" accept=".zip,.jpg,.jpeg,.png,.pdf,.docx,.xlsx,.pptx,.html,.php,.ino,.css,.js">
                                <div class="form-text" style="font-size: 11px; margin-top: 5px;">Mendukung PDF, DOCX, ZIP, Gambar, HTML, PHP, INO, dll. Maks 5MB.</div>
                            </div>
                        <?php else: ?>
                            <div class="mb-4 p-3 rounded text-center position-relative" style="background-color: #fffbeb; border: 1px dashed #f59e0b;">
                                <div class="position-absolute top-0 end-0 p-2"><i class="bi bi-lock-fill text-warning"></i></div>
                                <label class="form-label fw-bold small text-muted d-block"><i class="bi bi-paperclip"></i> Lampirkan Dokumen</label>
                                <input class="form-control form-control-sm opacity-50" type="file" disabled>
                                <div class="form-text mt-2" style="font-size: 11px; color: #b45309;">
                                    Upload file (PDF, Word, ZIP, Gambar, Koding) eksklusif untuk <b>Akun PRO</b>. 
                                    <br><a href="upgrade_pro.php" class="fw-bold text-decoration-underline" style="color: #d97706;">Buka Fitur Ini</a>
                                </div>
                            </div>
                        <?php endif; ?>

                        <button type="submit" class="btn btn-primary w-100 fw-bold rounded-pill">
                            <i class="bi bi-send-fill"></i> Simpan & Aktifkan
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- TABEL DAFTAR TUGAS -->
        <div class="col-md-8 mb-4">
            <div class="card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="fw-bold mb-0">Daftar Tugas Aktif</h5>
                        <small class="text-muted"><i class="bi bi-info-circle"></i> Otomatis terhapus dlm <?= $masa_aktif_hari ?> hari.</small>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>Prompt Pemicu</th>
                                    <th>Cuplikan Isi Pesan</th>
                                    <th>Dibuat</th>
                                    <th class="text-center">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($data_tugas)): ?>
                                    <tr><td colspan="4" class="text-center text-muted py-4 fst-italic">Belum ada tugas yang aktif.</td></tr>
                                <?php else: ?>
                                    <?php foreach($data_tugas as $tugas): ?>
                                    <tr>
                                        <td><span class="badge bg-dark"><?= htmlspecialchars($tugas['trigger_prompt']) ?></span></td>
                                        <td>
                                            <span class="d-inline-block text-truncate" style="max-width: 180px; font-size: 13px;">
                                                <?= htmlspecialchars($tugas['deskripsi_tugas']) ?>
                                            </span>
                                        </td>
                                        <td style="font-size: 12px; color: #64748b; white-space: nowrap;">
                                            <?= date('d M Y', strtotime($tugas['created_at'])) ?>
                                        </td>
                                        <td class="text-center">
                                            
                                            <!-- UI HAPUS TUGAS: DINAMIS BERDASARKAN STATUS AKUN -->
                                            <?php if($is_pro): ?>
                                                <a href="?hapus=<?= $tugas['id'] ?>" class="btn btn-sm btn-danger rounded-circle shadow-sm" onclick="return confirm('Yakin ingin menghapus tugas ini?');" title="Hapus">
                                                    <i class="bi bi-trash"></i>
                                                </a>
                                            <?php else: ?>
                                                <button type="button" class="btn btn-sm btn-secondary rounded-circle shadow-sm opacity-50" onclick="alert('🔒 FITUR TERKUNCI!\n\nAkun FREE tidak dapat menghapus tugas secara manual.\n\nTugas ini akan hilang OTOMATIS setelah <?= $masa_aktif_hari ?> hari semenjak dibuat. Jika ingin akses kontrol penuh, silakan Upgrade ke Paket PRO.');" title="Terkunci (Hanya PRO)">
                                                    <i class="bi bi-lock-fill"></i>
                                                </button>
                                            <?php endif; ?>

                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>