<?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';

// Fetch all categories
$categories = mysqli_query($conn, 'SELECT id, category_name FROM categories');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate posted data
    $category_id = intval($_POST['category_id']);
    $product_name = trim($_POST['product_name']);
    $old_price = floatval($_POST['old_price']);
    $current_price = floatval($_POST['current_price']);
    $quantity = intval($_POST['quantity']);


    $mode = trim($_POST['mode']);

    // Calculate discount percentage
    $discount = ($old_price > 0) ? (($old_price - $current_price) / $old_price) * 100 : 0;

    try {
        $stmt = $conn->prepare(
            'INSERT INTO products (category_id, product_name, old_price, current_price, discount, quantity,   mode) 
            VALUES (?, ?, ?, ?, ?, ?,  ?)'
        );
        $stmt->bind_param("isdddss", $category_id, $product_name, $old_price, $current_price, $discount, $quantity,   $mode);
        $stmt->execute();

        // Get the last inserted product ID
        $product_id = $stmt->insert_id;

        // Process uploaded images
    if (isset($_FILES['product_images'])) {
    $fileCount = count($_FILES['product_images']['name']);
    for ($i = 0; $i < $fileCount; $i++) {
        if ($_FILES['product_images']['error'][$i] === UPLOAD_ERR_OK) {
            $photoTmpName = $_FILES['product_images']['tmp_name'][$i];
            $photoInfo = @getimagesize($photoTmpName);
            $imageFormat = strtolower(pathinfo($_FILES["product_images"]["name"][$i], PATHINFO_EXTENSION));
            $photoName = uniqid() . "." . $imageFormat;
            $photoDestination = 'uploads/' . $photoName;

            // Validate and resize the image if needed
            if ($photoInfo !== false) {
                if ($_FILES['product_images']['size'][$i] > 200000) {
                    try {
                        // Call the resizeImage function
                        resizeImage($photoTmpName, $photoDestination, $imageFormat);
                    } catch (Exception $e) {
                        echo "Image resizing failed: " . $e->getMessage();
                    }
                } else {
                    move_uploaded_file($photoTmpName, $photoDestination);
                }

                // Insert image path into the database
                $stmt = $conn->prepare('INSERT INTO product_images (product_id, image_path) VALUES (?, ?)');
                $stmt->bind_param("is", $product_id, $photoDestination);
                $stmt->execute();
            }
        }
    }
}


        echo "Product posted successfully.";
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
}

// Function to resize the image
function resizeImage($source, $destination, $format) {
    $maxWidth = 800;
    $maxHeight = 800;

    // Create an image resource from the source based on its format
    switch ($format) {
        case 'jpeg':
        case 'jpg':
            $sourceImage = @imagecreatefromjpeg($source);
            break;
        case 'png':
            $sourceImage = @imagecreatefrompng($source);
            break;
        case 'gif':
            $sourceImage = @imagecreatefromgif($source);
            break;
        default:
            throw new Exception("Unsupported image format: $format");
    }

    // Check if the source image was created successfully
    if (!$sourceImage) {
        throw new Exception("Failed to create image resource. The file may not be a valid $format image.");
    }

    // Get original dimensions
    list($originalWidth, $originalHeight) = getimagesize($source);

    // Calculate new dimensions
    $ratio = min($maxWidth / $originalWidth, $maxHeight / $originalHeight);
    $newWidth = intval($originalWidth * $ratio);
    $newHeight = intval($originalHeight * $ratio);

    // Create a new blank image with the new dimensions
    $resizedImage = imagecreatetruecolor($newWidth, $newHeight);

    // Preserve transparency for PNG and GIF
    if ($format === 'png' || $format === 'gif') {
        imagealphablending($resizedImage, false);
        imagesavealpha($resizedImage, true);
    }

    // Resize the image
    imagecopyresampled($resizedImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

    // Save the resized image to the destination
    switch ($format) {
        case 'jpeg':
        case 'jpg':
            imagejpeg($resizedImage, $destination, 90);
            break;
        case 'png':
            imagepng($resizedImage, $destination);
            break;
        case 'gif':
            imagegif($resizedImage, $destination);
            break;
    }

    // Free resources
    imagedestroy($sourceImage);
    imagedestroy($resizedImage);
}

?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Post Product</title>
    <script>
        function addImageInput() {
            const imageContainer = document.getElementById('imageContainer');
            const totalImages = imageContainer.querySelectorAll('input[type="file"]').length;

            if (totalImages < 5) {
                const input = document.createElement('input');
                input.type = 'file';
                input.name = 'product_images[]';
                imageContainer.appendChild(input);
            }
        }

        function removeImageInput() {
            const imageContainer = document.getElementById('imageContainer');
            const inputs = imageContainer.querySelectorAll('input[type="file"]');
            if (inputs.length > 1) {
                imageContainer.removeChild(inputs[inputs.length - 1]);
            }
        }
    </script>
    <style>/* General reset */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* Body styling */
body {
    font-family: Arial, sans-serif;
    background-color: #f9f9f9;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

/* Form container styling */
form {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    padding: 20px;
    max-width: 400px;
    width: 100%;
    margin: 20px;
}

/* Form title */
form h1 {
    text-align: center;
    font-size: 1.5rem;
    margin-bottom: 20px;
    color: #333;
}

/* Label styling */
form label {
    display: block;
    font-size: 0.9rem;
    margin-bottom: 5px;
    color: #555;
}

/* Input and select styling */
form input[type="text"],
form input[type="number"],
form select,
form input[type="file"] {
    width: 100%;
    padding: 10px;
    margin-bottom: 15px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 0.9rem;
}

/* Button styling */
form button {
    display: inline-block;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 4px;
    padding: 10px 15px;
    font-size: 0.9rem;
    cursor: pointer;
    transition: background-color 0.3s;
    margin-right: 5px;
}

form button:hover {
    background-color: #0056b3;
}

/* Image container buttons */
form button[type="button"] {
    background-color: #28a745;
}

form button[type="button"]:hover {
    background-color: #218838;
}

/* File input container */
#imageContainer {
    margin-bottom: 15px;
}

/* Responsive styling */
@media (max-width: 500px) {
    form {
        padding: 15px;
    }

    form button {
        width: 100%;
        margin-bottom: 10px;
    }
}
</style>
</head>
<body>
    <form method="POST" action="post_product.php" enctype="multipart/form-data">
        <label for="category">Category:</label>
        <select id="category" name="category_id" required>
            <option value="">Select Category</option>
            <?php while ($row = mysqli_fetch_assoc($categories)) : ?>
                <option value="<?= htmlspecialchars($row['id']) ?>"><?= htmlspecialchars($row['category_name']) ?></option>
            <?php endwhile; ?>
        </select><br>

        <label for="product_name">Product Name:</label>
        <input type="text" name="product_name" required><br>

        <label for="old_price">Old Price:</label>
        <input type="number" step="0.01" name="old_price" required><br>

        <label for="current_price">Current Price:</label>
        <input type="number" step="0.01" name="current_price" required><br>

        <label for="quantity">Quantity:</label>
        <input type="number" name="quantity" required><br>

        <label for="mode">Mode:</label>
        <select name="mode" required>
            <option value="old">Old</option>
            <option value="new">New</option>
        </select><br>

        <div id="imageContainer">
            <label>Product Images (1-5):</label><br>
            <input type="file" name="product_images[]" required>
        </div>
        <button type="button" onclick="addImageInput()">Add Image</button>
        <button type="button" onclick="removeImageInput()">Remove Image</button><br><br>

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