<?php

include "db.php";

header("Content-Type: application/json");

if(!isset($_FILES['gambar'])){
echo json_encode(["status"=>"error","msg"=>"file tidak ada"]);
exit;
}

$type = $_POST['type'] ?? 'slide';

$path = __DIR__."/uploads/".$type."/";

if(!is_dir($path)){
mkdir($path,0777,true);
}

foreach($_FILES['gambar']['name'] as $i=>$name){

$tmp = $_FILES['gambar']['tmp_name'][$i];

if(!$tmp) continue;

$clean = preg_replace("/[^a-zA-Z0-9._-]/","",$name);

$filename = time().'_'.$i.'_'.$clean;

move_uploaded_file($tmp,$path.$filename);

/* INSERT DATABASE */

$q = mysqli_query($conn,"
INSERT INTO media(gambar,created_at)
VALUES('$filename',NOW())
");

/* cek error */

if(!$q){
echo json_encode([
"status"=>"error",
"msg"=>mysqli_error($conn)
]);
exit;
}

}

echo json_encode(["status"=>"ok"]);