<?php

include '../koneksi.php';

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

$jam_buka = $_POST['jam_buka'] ?? null;
$jam_tutup = $_POST['jam_tutup'] ?? null;
$buka_24_jam = $_POST['buka_24_jam'] ?? 0;
$foto = '';

if(isset($_FILES['foto'])){

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

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

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

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

        echo json_encode([
            'status'=>'error',
            'message'=>'Format file tidak valid'
        ]);

        exit;

    }

    move_uploaded_file(

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

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

    );

    $foto = $namaFile;

}

$query = mysqli_query(
    $conn,
    "INSERT INTO spbu
    (
        nama_spbu,
        alamat,
        latitude,
        longitude,
        foto,
        jam_buka,
        jam_tutup,
        buka_24_jam
    )
    VALUES
    (
        '$nama',
        '$alamat',
        '$lat',
        '$lng',
        '$foto',
        '$jam_buka',
        '$jam_tutup',
        '$buka_24_jam'
    )"
);

if($query){

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

}else{

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

}