<?php
include "../../config/master.php";

$id = $_POST['id'];

$name = mysqli_real_escape_string($conn,$_POST['anganwadi_name']);
$location = mysqli_real_escape_string($conn,$_POST['location']);
$description = mysqli_real_escape_string($conn,$_POST['description']);

$data = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM village_anganwadi WHERE id='$id'"));
$image = $data['image'];

if(isset($_FILES['image']) && $_FILES['image']['error'] == 0)
{
$target_dir="../../uploads/anganwadi/";

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

$ext = strtolower(pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION));
$allowed=['jpg','jpeg','png','webp'];

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

if(!empty($image) && file_exists($target_dir.$image)){
unlink($target_dir.$image);
}

$image="anganwadi_".time().rand(100,999).".".$ext;

move_uploaded_file($_FILES['image']['tmp_name'],$target_dir.$image);
}
}

mysqli_query($conn,"
UPDATE village_anganwadi SET
anganwadi_name='$name',
location='$location',
description='$description',
image='$image'
WHERE id='$id'
");

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