<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Blog</title>
    <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
</head>
<body>

<?php

include "db.php"; 

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $title = mysqli_real_escape_string($conn, $_POST['blog_title']);
    $content = mysqli_real_escape_string($conn, $_POST['blog_content']);

    date_default_timezone_set('Asia/Kolkata');
    $created_at = date('Y-m-d H:i:s');

    $image = '';
    if (!empty($_FILES['blog_image']['name'])) {
        $imageName = $_FILES['blog_image']['name'];
        $targetDir = "blogs/";
        $targetFile = $targetDir . $imageName;

        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0777, true);
        }

        if (move_uploaded_file($_FILES['blog_image']['tmp_name'], $targetFile)) {
            $image = $imageName;
        }
    }

    $sql = "INSERT INTO blogs (title, image, content, created_at) 
            VALUES ('$title', '$image', '$content', '$created_at')";

    if (mysqli_query($conn, $sql)) {
        echo "
        <script>
        Swal.fire({
            icon: 'success',
            title: 'Blog added successfully!',
            showConfirmButton: false,
            timer: 2000
        }).then(() => {
            window.location.href = 'blog.php';
        });
        </script>";
    } else {
        echo "
        <script>
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'Something went wrong while adding the blog.',
        }).then(() => {
            window.history.back();
        });
        </script>";
    }
}

?>
    
</body>
</html>