<?php

session_start();

require_once "../config/koneksi.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$id = intval($_POST['id']);
$judul = trim($_POST['judul']);
$isi = trim($_POST['isi']);


// Ambil foto lama

$query = "SELECT foto FROM sambutan WHERE id = ?";

$stmt = mysqli_prepare($koneksi, $query);

mysqli_stmt_bind_param($stmt, "i", $id);

mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);

$data = mysqli_fetch_assoc($result);

$foto_lama = $data['foto'] ?? '';


// Foto tetap menggunakan foto lama

$nama_foto = $foto_lama;


// Jika admin memilih foto baru

if (
    isset($_FILES['foto']) &&
    $_FILES['foto']['error'] === UPLOAD_ERR_OK
) {

    $nama_asli = $_FILES['foto']['name'];

    $tmp = $_FILES['foto']['tmp_name'];

    $ekstensi = strtolower(
        pathinfo(
            $nama_asli,
            PATHINFO_EXTENSION
        )
    );


    // Nama foto baru

    $nama_foto =
        'kepala-dinas-' .
        time() .
        '.' .
        $ekstensi;


    // Lokasi penyimpanan

    $folder =
        "../uploads/kepala-dinas/";


    // Upload foto

    move_uploaded_file(
        $tmp,
        $folder . $nama_foto
    );


    // Hapus foto lama

    if (
        !empty($foto_lama) &&
        file_exists(
            $folder . $foto_lama
        )
    ) {

        unlink(
            $folder . $foto_lama
        );
    }
}


// Update database

$sql = "
    UPDATE sambutan
    SET
        judul = ?,
        isi = ?,
        foto = ?
    WHERE id = ?
";

$stmt = mysqli_prepare(
    $koneksi,
    $sql
);

mysqli_stmt_bind_param(
    $stmt,
    "sssi",
    $judul,
    $isi,
    $nama_foto,
    $id
);

mysqli_stmt_execute($stmt);


// Kembali ke edit

header(
    "Location: edit-sambutan.php?success=1"
);

exit;
