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

$nama_sekolah = mysqli_real_escape_string($host, $_POST['nama_sekolah']);
$slogan_sekolah = mysqli_real_escape_string($host, $_POST['slogan_sekolah']);

// Handle logo upload
$logo_sekolah = '';
if (!empty($_FILES['logo_sekolah']['name'])) {
    $target_dir = "upload/";
    $target_file = $target_dir . basename($_FILES["logo_sekolah"]["name"]);
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["logo_sekolah"]["tmp_name"]);
    if ($check !== false) {
        // Generate unique name
        $unique_name = time() . '_' . uniqid() . '.' . $imageFileType;
        $target_file = $target_dir . $unique_name;

        if (move_uploaded_file($_FILES["logo_sekolah"]["tmp_name"], $target_file)) {
            $logo_sekolah = $unique_name;
        } else {
            echo "<script>alert('Sorry, there was an error uploading your file.'); window.location.href='manage_namasekolah.php';</script>";
            exit;
        }
    } else {
        echo "<script>alert('File is not an image.'); window.location.href='manage_namasekolah.php';</script>";
        exit;
    }
} else {
    // If no new logo, keep the old one
    $query_old = "SELECT logo_sekolah FROM sekolah";
    $result_old = mysqli_query($host, $query_old);
    $row_old = mysqli_fetch_assoc($result_old);
    $logo_sekolah = $row_old['logo_sekolah'];
}

// Update the database
$query = "UPDATE sekolah SET nama_sekolah='$nama_sekolah', slogan_sekolah='$slogan_sekolah', logo_sekolah='$logo_sekolah'";
if (mysqli_query($host, $query)) {
    echo "<script>alert('Data sekolah berhasil diupdate!'); window.location.href='manage_namasekolah.php';</script>";
} else {
    echo "<script>alert('Error updating record: " . mysqli_error($host) . "'); window.location.href='manage_namasekolah.php';</script>";
}
?>
