<?php

include '../koneksi.php';
header('Content-Type: application/json');

$id = $_POST['id'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];

$fotoLama = '';

$jam_buka = $_POST['jam_buka'];
$jam_tutup = $_POST['jam_tutup'];
$buka_24_jam = $_POST['buka_24_jam'];

$getData = mysqli_query(
    $conn,
    "SELECT foto
    FROM spbu
    WHERE id='$id'"
);

if($row = mysqli_fetch_assoc($getData)){

    $fotoLama = $row['foto'];

}

$updateFoto = "";

$hapusFotoLama = false;

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

    $namaFile =
    time().'_'.
    $_FILES['foto']['name'];

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

    $fileType = strtolower(
        pathinfo(
            $_FILES['foto']['name'],
            PATHINFO_EXTENSION
        )
    );

    if(!in_array($fileType, $allowed)){

        echo json_encode([
            'status'=>'error',
            'message'=>'File type not allowed'
        ]);

        exit;

    }

    move_uploaded_file(

        $_FILES['foto']['tmp_name'],

        '../uploads/spbu/' .
        $namaFile

    );

    $updateFoto =
    ", foto='$namaFile'";

    $hapusFotoLama = true;

}

$query = mysqli_query(

    $conn,

    "UPDATE spbu SET

    nama_spbu='$nama',
    alamat='$alamat',
    latitude='$lat',
    longitude='$lng',
    jam_buka='$jam_buka',
    jam_tutup='$jam_tutup',
    buka_24_jam='$buka_24_jam'
    $updateFoto

    WHERE id='$id'
    "
);

if($query){

    if(
        $hapusFotoLama &&
        !empty($fotoLama) &&
        file_exists(
            '../uploads/spbu/' .
            $fotoLama
        )
    ){

        unlink(
            '../uploads/spbu/' .
            $fotoLama
        );

    }

    echo json_encode([
        'status'=>'success'
    ]);

} else{

    echo json_encode([
        'status'=>'error',
        'message'=>mysqli_error($conn)
    ]);

}