<?php
session_start();

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Include the database connection
require 'db_connection.php';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $category = intval($_POST['category']);
    $title = htmlspecialchars($_POST['title']);
    $details = htmlspecialchars($_POST['details']);
    $url = isset($_POST['url']) ? htmlspecialchars($_POST['url']) : null;

    $imagePaths = []; // Array to hold paths of uploaded images

    // Loop through uploaded files
    foreach ($_FILES['images']['tmp_name'] as $key => $tmpName) {
        if (isset($tmpName) && $_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
            $imageName = basename($_FILES['images']['name'][$key]);
            $imagePath = 'uploads/' . uniqid() . '_' . $imageName;

            // Resize the image if it's larger than 50KB
            if ($_FILES['images']['size'][$key] > 51200) { // 50KB
                $image = imagecreatefromstring(file_get_contents($tmpName));
                if ($image) {
                    $width = imagesx($image);
                    $height = imagesy($image);
                    $newWidth = 800; // Resize width
                    $newHeight = intval($height * $newWidth / $width);
                    $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
                    imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                    imagejpeg($resizedImage, $imagePath, 85); // Save resized image
                    imagedestroy($resizedImage);
                }
                imagedestroy($image);
            } else {
                // Save the original image if no resizing is needed
                move_uploaded_file($tmpName, $imagePath);
            }

            // Add the image path to the array
            $imagePaths[] = $imagePath;
        }
    }

    // Insert data into the database
    $stmt = $conn->prepare("INSERT INTO articles (category_id, title, details, url, images) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param(
        'issss',
        $category,
        $title,
        $details,
        $url,
        json_encode($imagePaths) // Save all image paths as JSON
    );

    if ($stmt->execute()) {
        echo "Article posted successfully with " . count($imagePaths) . " images.";
    } else {
        echo "Error: " . $stmt->error;
    }
}
?>

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Article</title>
    <style>/* General Reset */
body {
    margin: 0;
    font-family: Arial, sans-serif;
    line-height: 1.6;
    background-color: #f4f4f9;
    color: #333;
}

/* Page Container */
h1 {
    text-align: center;
    margin-top: 20px;
    color: #444;
}

form {
    width: 90%;
    max-width: 600px;
    margin: 20px auto;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* Form Labels */
label {
    display: block;
    font-weight: bold;
    margin-bottom: 8px;
    color: #555;
}

/* Form Inputs */
input[type="text"],
input[type="url"],
textarea,
select {
    width: 100%;
    padding: 10px;
    margin-bottom: 15px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
}

/* Focused Inputs */
input:focus,
textarea:focus,
select:focus {
    border-color: #007BFF;
    outline: none;
    box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}

/* File Upload */
.image-field {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.image-field input[type="file"] {
    flex: 1;
    padding: 5px;
}

.image-field button {
    margin-left: 10px;
    background-color: #dc3545;
    border: none;
    color: #fff;
    padding: 5px 10px;
    font-size: 14px;
    border-radius: 4px;
    cursor: pointer;
}

.image-field button:hover {
    background-color: #c82333;
}

/* Add Image Button */
#image-container {
    margin-bottom: 15px;
}

button {
    display: inline-block;
    background-color: #28a745;
    color: #fff;
    border: none;
    padding: 10px 15px;
    font-size: 16px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

button:hover {
    background-color: #218838;
}

/* Optional Alert for Image Limit */
.alert {
    color: #dc3545;
    font-size: 14px;
    margin-bottom: 10px;
}

/* Responsiveness */
@media (max-width: 600px) {
    form {
        padding: 15px;
    }

    button {
        font-size: 14px;
        padding: 8px 12px;
    }
}
</style>
    <script>
        function addImageField() {
            const imageContainer = document.getElementById('image-container');
            const imageFields = imageContainer.querySelectorAll('.image-field');
            if (imageFields.length < 5) {
                const newField = document.createElement('div');
                newField.classList.add('image-field');
                newField.innerHTML = `
                    <input type="file" name="images[]" accept="image/*">
                    <button type="button" onclick="removeImageField(this)">Remove</button>
                `;
                imageContainer.appendChild(newField);
            } else {
                alert('You can only upload up to 5 images.');
            }
        }

        function removeImageField(button) {
            button.parentElement.remove();
        }
    </script>
</head>
<body>
    <h1>Create Article</h1>
    <form method="post" enctype="multipart/form-data">
        <label for="category">Category:</label><br>
        <select id="category" name="category" required>
            <option value="">Select a Category</option>
            <?php
            $result = $conn->query("SELECT id, name FROM cateories");
            while ($row = $result->fetch_assoc()) {
                echo "<option value=\"{$row['id']}\">" . htmlspecialchars($row['name']) . "</option>";
            }
            ?>
        </select><br><br>

        <label for="title">Article Title:</label><br>
        <input type="text" id="title" name="title" required><br><br>

        <label for="details">Details:</label><br>
        <textarea id="details" name="details" rows="5" required></textarea><br><br>

        <label for="url">URL Link (optional):</label><br>
        <input type="url" id="url" name="url"><br><br>

        <label>Upload Images:</label><br>
        <div id="image-container">
            <div class="image-field">
                <input type="file" name="images[]" accept="image/*" required>
            </div>
        </div>
      

        <button type="submit">Post Article</button>
    </form>
</body>
</html>
