<?php
session_start();
if (!isset($_SESSION['admin_logged_in'])) { header("Location: login.php"); exit(); }
include '../db_connect.php';

// Handle Add Tip
if (isset($_POST['add_tip'])) {
    $title = $_POST['title'];
    $content = $_POST['content'];
    
    // Image Upload
    $target_dir = "../assets/tips/";
    if (!file_exists($target_dir)) { mkdir($target_dir, 0777, true); }
    
    $file_name = time() . "_" . basename($_FILES["image"]["name"]);
    $target_file = $target_dir . $file_name;
    
    if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
        $db_path = "assets/tips/" . $file_name;
        $stmt = $conn->prepare("INSERT INTO health_tips (title, image, content) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $title, $db_path, $content);
        $stmt->execute();
        $msg = "Health Tip Published!";
    } else {
        $msg = "Image Upload Failed.";
    }
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $conn->query("DELETE FROM health_tips WHERE id=$id");
    header("Location: manage_tips.php");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Health Tips</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 p-6">
    <nav class="mb-6 flex gap-4">
        <a href="dashboard.php" class="text-blue-600 font-bold">← Back to Dashboard</a>
    </nav>

    <div class="grid md:grid-cols-3 gap-8">
        <div class="bg-white p-6 rounded shadow-md h-fit">
            <h2 class="text-xl font-bold mb-4">Write New Health Tip</h2>
            <?php if(isset($msg)) echo "<p class='text-green-600 mb-4'>$msg</p>"; ?>
            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <div>
                    <label class="block text-sm text-gray-600">Article Title</label>
                    <input type="text" name="title" required class="w-full border p-2 rounded">
                </div>
                <div>
                    <label class="block text-sm text-gray-600">Cover Image</label>
                    <input type="file" name="image" required class="w-full border p-2 rounded">
                </div>
                <div>
                    <label class="block text-sm text-gray-600">Content / Advice</label>
                    <textarea name="content" rows="6" required class="w-full border p-2 rounded"></textarea>
                </div>
                <button type="submit" name="add_tip" class="w-full bg-green-600 text-white py-2 rounded hover:bg-green-700">Publish Article</button>
            </form>
        </div>

        <div class="md:col-span-2 space-y-4">
            <h2 class="text-xl font-bold">Published Articles</h2>
            <?php
            $result = $conn->query("SELECT * FROM health_tips ORDER BY id DESC");
            while($row = $result->fetch_assoc()) {
                echo '<div class="bg-white p-4 rounded shadow flex gap-4">';
                // Check if image path starts with assets (new uploads) or is default
                $imgSrc = (strpos($row['image'], 'assets') === 0) ? '../'.$row['image'] : 'https://via.placeholder.com/150';
                
                echo '<img src="' . $imgSrc . '" class="w-24 h-24 object-cover rounded">';
                echo '<div class="flex-1">';
                echo '<h3 class="font-bold text-lg text-gray-800">' . $row['title'] . '</h3>';
                echo '<p class="text-sm text-gray-500 mb-2">' . substr($row['content'], 0, 100) . '...</p>';
                echo '<span class="text-xs text-gray-400">Posted: ' . date('d M Y', strtotime($row['created_at'])) . '</span>';
                echo '</div>';
                echo '<a href="manage_tips.php?delete=' . $row['id'] . '" class="text-red-500 text-sm hover:underline self-start" onclick="return confirm(\'Delete this article?\')">Delete</a>';
                echo '</div>';
            }
            ?>
        </div>
    </div>
</body>
</html>