<?php
include 'koneksi.php';
session_start();
if (!isset($_SESSION['login_admin'])) {
    header('Location: dashboard.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Handle image upload if provided
    if (!empty($_FILES['gambar']['name'])) {
        $target_dir = "upload/";
        $unique_name = time() . '_' . basename($_FILES["gambar"]["name"]);
        $target_file = $target_dir . $unique_name;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        // Check if image file is a actual image or fake image
        $check = getimagesize($_FILES["gambar"]["tmp_name"]);
        if ($check !== false) {
            // Allow certain file formats
            if ($imageFileType == "jpg" || $imageFileType == "png" || $imageFileType == "jpeg" || $imageFileType == "gif") {
                if (move_uploaded_file($_FILES["gambar"]["tmp_name"], $target_file)) {
                    // Update gambar in tb_struktur_sekolah
                    $query_gambar = "UPDATE tb_struktur_sekolah SET gambar='$unique_name'";
                    if (mysqli_query($host, $query_gambar)) {
                        echo "<script>alert('Gambar struktur organisasi berhasil diupdate!'); window.location.href='edit_struktur.php';</script>";
                    } else {
                        echo "<script>alert('Error updating record: " . mysqli_error($host) . "'); window.location.href='edit_struktur.php';</script>";
                    }
                } else {
                    echo "<script>alert('Sorry, there was an error uploading your file.'); window.location.href='edit_struktur.php';</script>";
                }
            } else {
                echo "<script>alert('Sorry, only JPG, JPEG, PNG & GIF files are allowed.'); window.location.href='edit_struktur.php';</script>";
            }
        } else {
            echo "<script>alert('File is not an image.'); window.location.href='edit_struktur.php';</script>";
        }
    } else {
        echo "<script>alert('Tidak ada gambar yang dipilih.'); window.location.href='edit_struktur.php';</script>";
    }
}
?>

