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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $id = mysqli_real_escape_string($host, $_POST['id_deskripsi']);
    $judul = mysqli_real_escape_string($host, $_POST['judul']);
    $paragraf = mysqli_real_escape_string($host, $_POST['paragraf']);

    // Handle file upload
    $gambar = '';
    if (isset($_FILES['gambar']) && $_FILES['gambar']['error'] == 0) {
        $target_dir = "upload/";
        $target_file = $target_dir . basename($_FILES["gambar"]["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) {
            if (move_uploaded_file($_FILES["gambar"]["tmp_name"], $target_file)) {
                $gambar = basename($_FILES["gambar"]["name"]);
            } else {
                echo "Sorry, there was an error uploading your file.";
                exit;
            }
        } else {
            echo "File is not an image.";
            exit;
        }
    }

    // If no new image, keep the old one
    if (empty($gambar)) {
        $query_old = "SELECT gambar_deskripsi_sekolah FROM deskripsi_sekolah WHERE id_deskripsi='$id'";
        $result_old = mysqli_query($host, $query_old);
        $row_old = mysqli_fetch_assoc($result_old);
        $gambar = $row_old['gambar_deskripsi_sekolah'];
    }

    $query = "UPDATE deskripsi_sekolah SET judul_selamatdatang='$judul', paragraf_1='$paragraf', gambar_deskripsi_sekolah='$gambar' WHERE id_deskripsi='$id'";
    if (mysqli_query($host, $query)) {
        echo "<script>alert('Update berhasil!'); window.location.href='dashboard_admin.php';</script>";
    } else {
        echo "Error updating record: " . mysqli_error($host);
    }
}
?>
