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

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nama = mysqli_real_escape_string($host, $_POST['nama']);
    $paragraf1 = mysqli_real_escape_string($host, $_POST['paragraf1']);
    $paragraf2 = mysqli_real_escape_string($host, $_POST['paragraf2']);
    $paragraf3 = mysqli_real_escape_string($host, $_POST['paragraf3']);
    $paragraf4 = mysqli_real_escape_string($host, $_POST['paragraf4']);
    $paragraf5 = mysqli_real_escape_string($host, $_POST['paragraf5']);

    // Update nama in tb_guru
    $query_nama = "UPDATE tb_guru SET nama_guru='$nama' WHERE jabatan='kepalasekolah'";
    mysqli_query($host, $query_nama);

    // 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_guru
                    $query_gambar = "UPDATE tb_guru SET gambar_guru='$unique_name' WHERE jabatan='kepalasekolah'";
                    mysqli_query($host, $query_gambar);
                } else {
                    echo "<script>alert('Sorry, there was an error uploading your file.'); window.location.href='edit_detail_kepsek.php';</script>";
                    exit;
                }
            } else {
                echo "<script>alert('Sorry, only JPG, JPEG, PNG & GIF files are allowed.'); window.location.href='edit_detail_kepsek.php';</script>";
                exit;
            }
        } else {
            echo "<script>alert('File is not an image.'); window.location.href='edit_detail_kepsek.php';</script>";
            exit;
        }
    }

    // Update paragraphs in tb_katakata_kepsek
    $query_paragraf = "UPDATE tb_katakata_kepsek SET paragraf_1='$paragraf1', paragraf_2='$paragraf2', paragraf_3='$paragraf3', paragraf_4='$paragraf4', paragraf_5='$paragraf5' WHERE id_kepsek=1";
    if (mysqli_query($host, $query_paragraf)) {
        echo "<script>alert('Detail kepala sekolah berhasil diupdate!'); window.location.href='edit_detail_kepsek.php';</script>";
    } else {
        echo "<script>alert('Error updating record: " . mysqli_error($host) . "'); window.location.href='edit_detail_kepsek.php';</script>";
    }
}
?>

