<?php

session_start();

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


// ========================================
// CEK LOGIN ADMIN
// ========================================

if (!isset($_SESSION['user_id'])) {

    header("Location: ../login.php");
    exit;
}


// ========================================
// PASTIKAN REQUEST POST
// ========================================

if ($_SERVER["REQUEST_METHOD"] !== "POST") {

    header("Location: index.php");
    exit;
}


// ========================================
// AMBIL DATA DARI FORM
// ========================================

$id = (int) ($_POST['id'] ?? 0);

$judul = trim(
    $_POST['judul'] ?? ''
);

$isi = trim(
    $_POST['isi'] ?? ''
);

$tanggal = $_POST['tanggal'] ?? '';

$link_instagram = trim(
    $_POST['link_instagram'] ?? ''
);

// ========================================
// VALIDASI
// ========================================

if (
    $id <= 0 ||
    $judul === '' ||
    $isi === '' ||
    $tanggal === ''
) {

    header(
        "Location: edit.php?id=$id&error=1"
    );

    exit;
}


// ========================================
// AMBIL FOTO LAMA
// ========================================

$query_lama = "
    SELECT gambar
    FROM berita
    WHERE id = ?
    LIMIT 1
";

$stmt_lama = mysqli_prepare(
    $koneksi,
    $query_lama
);

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

mysqli_stmt_execute(
    $stmt_lama
);

$result_lama =
    mysqli_stmt_get_result(
        $stmt_lama
    );


if (
    mysqli_num_rows(
        $result_lama
    ) !== 1
) {

    header("Location: index.php");
    exit;
}


$data_lama =
    mysqli_fetch_assoc(
        $result_lama
    );


$nama_gambar =
    $data_lama['gambar'];


// ========================================
// PROSES FOTO BARU
// ========================================

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


    $folder_upload =
        "../../uploads/berita/";


    // Buat folder jika belum ada

    if (
        !is_dir(
            $folder_upload
        )
    ) {

        mkdir(
            $folder_upload,
            0777,
            true
        );
    }


    $nama_file =
        $_FILES['gambar']['name'];


    $tmp_file =
        $_FILES['gambar']['tmp_name'];


    $ukuran_file =
        $_FILES['gambar']['size'];


    // Ambil ekstensi file

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


    // Format yang diperbolehkan

    $format_diperbolehkan = [
        'jpg',
        'jpeg',
        'png',
        'webp'
    ];


    // Cek format

    if (
        !in_array(
            $ekstensi,
            $format_diperbolehkan
        )
    ) {

        header(
            "Location: edit.php?id=$id&error=format"
        );

        exit;
    }


    // Maksimal 2 MB

    if (
        $ukuran_file >
        2 * 1024 * 1024
    ) {

        header(
            "Location: edit.php?id=$id&error=ukuran"
        );

        exit;
    }


    // Buat nama file unik

    $nama_gambar =
        time() .
        "_" .
        uniqid() .
        "." .
        $ekstensi;


    $lokasi_file =
        $folder_upload .
        $nama_gambar;


    // Upload foto

    if (
        !move_uploaded_file(
            $tmp_file,
            $lokasi_file
        )
    ) {

        header(
            "Location: edit.php?id=$id&error=upload"
        );

        exit;
    }


    // ========================================
    // HAPUS FOTO LAMA
    // ========================================

    if (
        !empty($data_lama['gambar'])
    ) {


        $foto_lama =
            $folder_upload .
            $data_lama['gambar'];


        if (
            file_exists(
                $foto_lama
            )
        ) {

            unlink(
                $foto_lama
            );
        }
    }
}


// ========================================
// UPDATE DATA BERITA
// ========================================

$query_update = "
    UPDATE berita
    SET
        judul = ?,
        isi = ?,
        tanggal = ?,
        gambar = ?,
        link_instagram = ?
    WHERE id = ?
";


$stmt_update =
    mysqli_prepare(
        $koneksi,
        $query_update
    );


mysqli_stmt_bind_param(
    $stmt_update,
    "sssssi",
    $judul,
    $isi,
    $tanggal,
    $nama_gambar,
    $link_instagram,
    $id
);


// ========================================
// SIMPAN PERUBAHAN
// ========================================

if (
    mysqli_stmt_execute(
        $stmt_update
    )
) {

    header(
        "Location: index.php?success=edit"
    );

    exit;
}


// ========================================
// JIKA GAGAL
// ========================================

header(
    "Location: edit.php?id=$id&error=database"
);

exit;
