<?php
    $LINK 
= mysqli_connect('127.0.0.1','pisjo950','vjPRjFTxDVIoG7)t','pisjo950');

    if(isset(
$_POST['update_id']))
    {
        
$id = $_POST['update_id'];
        
$title = $_POST['title'][$id];
        
$description = $_POST['description'][$id];
        
$year = $_POST['year'][$id];
        
$newImageName = null;

        
// Check if a new image was uploaded
        
if (isset($_FILES['picture']['name'][$id]) && $_FILES['picture']['error'][$id] == 0) {
            
$uploadDir = 'Images/';
            
$imageName = basename($_FILES['picture']['name'][$id]);
            
$targetPath = $uploadDir . $imageName;

            
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
            if (
in_array($_FILES['picture']['type'][$id], $allowedTypes)) {
                if (
move_uploaded_file($_FILES['picture']['tmp_name'][$id], $targetPath)) {
                    
$newImageName = $imageName;
                } else {
                    echo 
"Failed to upload new image.";
                }
            } else {
                echo 
"Invalid image type.";
            }
        }

        if (
$newImageName) {
            
$stmt = $LINK->prepare("UPDATE Adolescence SET title=?, description=?, year=?, picture=? WHERE id=?");
            
$stmt->bind_param("ssisi", $title, $description, $year, $newImageName, $id);
        } else {
            
$stmt = $LINK->prepare("UPDATE Adolescence SET title=?, description=?, year=? WHERE id=?");
            
$stmt->bind_param("ssii", $title, $description, $year, $id);
        }

        if (
$stmt->execute()) {
            echo 
"Updated successfully.";
        } else {
            echo 
"Error: " . $stmt->error;
        }
    }

    if(isset(
$_POST['remove_id']))
    {
        
$id = $_POST['remove_id'];
        
$statement3 = $LINK->prepare("DELETE FROM Adolescence WHERE id=?");
        
$statement3->bind_param('i', $id);
        
$statement3->execute();
    }


    
header("Location: cms.php");
?>