<?php
// File: user.php
// Halaman dashboard pengguna biasa
include 'db.php';

// Periksa apakah pengguna sudah login
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$message = '';
$error = '';

// Tangani unggahan postingan baru
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $visibility = $_POST['visibility'] ?? 'public';
    $pin = '';

    if ($visibility === 'pin_protected') {
        $pin = trim($_POST['pin'] ?? '');
    }

    if (empty($title) || empty($content)) {
        $error = 'Judul dan konten tidak boleh kosong.';
    } elseif ($visibility === 'pin_protected' && empty($pin)) {
        $error = 'Anda harus memasukkan PIN untuk postingan yang dilindungi.';
    } else {
        $imageData = null;
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = 'uploads/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            $fileName = uniqid() . '-' . basename($_FILES['image']['name']);
            $uploadPath = $uploadDir . $fileName;

            if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadPath)) {
                $imageData = $uploadPath;
            } else {
                $error = 'Gagal mengunggah gambar.';
            }
        }

        if (empty($error)) {
            $newPost = [
                'title' => $title,
                'content' => $content,
                'pin' => $pin,
                'image' => $imageData,
                'user_id' => $_SESSION['user_id']
            ];
            if (savePost($newPost)) {
                $message = 'Postingan berhasil diunggah!';
            } else {
                $error = 'Gagal menyimpan postingan ke database.';
            }
        }
    }
}

// Data yang akan ditampilkan
$user_posts = getPostsByUserId($_SESSION['user_id']);
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Pengguna - yapping.</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <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=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');
        body {
            font-family: 'Inter', sans-serif;
            background-color: #fff;
            color: #000;
        }
        .title-font {
            font-family: 'Playfair Display', serif;
        }
    </style>
</head>
<body class="bg-white text-black p-4 sm:p-8 md:p-12 min-h-screen flex flex-col">
    <header class="flex items-center justify-between mb-12">
        <h1 class="text-4xl sm:text-5xl md:text-6xl font-bold title-font">yapping.</h1>
        <a href="logout.php" class="bg-black text-white px-6 py-2 rounded-full font-semibold hover:bg-gray-800 transition duration-300">
            Logout
        </a>
    </header>
    <main class="w-full flex-grow px-4 sm:px-8 md:px-12">
        <div class="mb-12">
            <h2 class="text-2xl font-bold mb-4">Unggah Postingan Baru</h2>
            <form action="user.php" method="POST" enctype="multipart/form-data" class="bg-gray-100 border border-gray-300 rounded-xl p-6 shadow-lg">
                <div class="mb-4">
                    <label for="title" class="block text-gray-700 font-bold mb-2">Judul Postingan</label>
                    <input type="text" id="title" name="title" class="bg-white text-black border-gray-300 rounded-md p-3 w-full" required>
                </div>
                <div class="mb-4">
                    <label for="content" class="block text-gray-700 font-bold mb-2">Konten (Tuliskan cerita keseharian Anda)</label>
                    <textarea id="content" name="content" rows="10" class="bg-white text-black border-gray-300 rounded-md p-3 w-full" required></textarea>
                </div>
                <div class="mb-4">
                    <label class="block text-gray-700 font-bold mb-2">Visibilitas Postingan</label>
                    <div class="flex items-center mb-2">
                        <input type="radio" id="public" name="visibility" value="public" checked onchange="togglePinInput()">
                        <label for="public" class="ml-2 text-black">Publik</label>
                    </div>
                    <div class="flex items-center">
                        <input type="radio" id="pin_protected" name="visibility" value="pin_protected" onchange="togglePinInput()">
                        <label for="pin_protected" class="ml-2 text-black">PIN</label>
                    </div>
                </div>
                <div id="pin-field" class="mb-4 hidden">
                    <label for="pin" class="block text-gray-700 font-bold mb-2">PIN untuk Membaca</label>
                    <input type="text" id="pin" name="pin" class="bg-white text-black border-gray-300 rounded-md p-3 w-full" placeholder="Contoh: 1234">
                </div>
                <div class="mb-4">
                    <label for="image" class="block w-full text-sm text-black file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-gray-200 file:text-black hover:file:bg-gray-300 transition duration-300">Unggah Gambar (Opsional)</label>
                    <input type="file" id="image" name="image" accept="image/*" class="block w-full text-sm text-black file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-gray-200 file:text-black hover:file:bg-gray-300 transition duration-300">
                </div>
                <button type="submit" class="w-full bg-black text-white font-bold py-3 px-4 rounded-lg hover:bg-gray-800 transition duration-300">
                    Unggah Postingan
                </button>
            </form>
        </div>

        <div class="mb-12">
            <h2 class="text-2xl font-bold mb-4">Daftar Postingan Anda</h2>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php if (empty($user_posts)): ?>
                    <p class="text-center text-gray-500 col-span-full">Belum ada postingan yang diunggah.</p>
                <?php else: ?>
                    <?php foreach ($user_posts as $post): ?>
                        <div class="bg-gray-100 border border-gray-300 rounded-xl p-6 shadow-lg flex flex-col justify-between">
                            <div>
                                <p class="text-lg font-bold"><?php echo htmlspecialchars($post['title']); ?></p>
                                <?php if (!empty($post['pin'])): ?>
                                    <p class="text-sm font-bold text-gray-800">PIN: <?php echo htmlspecialchars($post['pin']); ?></p>
                                <?php else: ?>
                                    <p class="text-sm font-bold text-green-600">Publik</p>
                                <?php endif; ?>
                            </div>
                            <form action="admin.php" method="POST" class="inline-block mt-4">
                                <input type="hidden" name="post_id" value="<?php echo htmlspecialchars($post['id']); ?>">
                                <input type="hidden" name="action" value="delete_post">
                                <button type="submit" class="w-full bg-red-600 text-white font-bold py-2 px-4 rounded-lg hover:bg-red-700 transition duration-300">
                                    Hapus
                                </button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </main>
    <footer class="text-center text-gray-500 mt-12 text-sm">
        <p>Hak Cipta &copy; <?php echo date('Y'); ?>. yapping.</p>
    </footer>
    <script>
        function togglePinInput() {
            const pinField = document.getElementById('pin-field');
            const pinInput = document.getElementById('pin');
            const pinProtectedRadio = document.getElementById('pin_protected');
            
            if (pinProtectedRadio.checked) {
                pinField.classList.remove('hidden');
                pinInput.setAttribute('required', 'required');
            } else {
                pinField.classList.add('hidden');
                pinInput.removeAttribute('required');
            }
        }
        
        // Panggil fungsi saat halaman dimuat untuk menyembunyikan input PIN secara default
        window.onload = togglePinInput;

        function showToast(message, bgColor) {
            const toast = document.createElement('div');
            toast.className = `fixed bottom-4 right-4 text-white px-6 py-3 rounded-lg shadow-xl ${bgColor} z-50 transition-transform transform translate-y-full`;
            toast.textContent = message;
            document.body.appendChild(toast);

            setTimeout(() => {
                toast.style.transform = 'translateY(0)';
            }, 100);

            setTimeout(() => {
                toast.style.transform = 'translateY(100%)';
                toast.addEventListener('transitionend', () => {
                    toast.remove();
                });
            }, 3000);
        }

        <?php if ($message): ?>
            showToast("<?php echo htmlspecialchars($message); ?>", 'bg-green-700');
        <?php endif; ?>

        <?php if ($error): ?>
            showToast("<?php echo htmlspecialchars($error); ?>", 'bg-red-700');
        <?php endif; ?>
    </script>
</body>
</html>