<?php

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

/* FETCH DISTRICTS */

$districts = mysqli_query($conn,"SELECT * FROM districts ORDER BY district_name");


/* SAVE WORK */

if(isset($_POST['save']))
{

$district_id = intval($_POST['district_id']);
$block_id    = intval($_POST['block_id']);
$village_id  = intval($_POST['village_id']);

$work_name   = trim($_POST['work_name']);
$target      = $_POST['target_amount'];

$status      = $_POST['status'];

$image = "";

/* IMAGE UPLOAD */

if(!empty($_FILES['image']['name']))
{

$filename = time()."_".$_FILES['image']['name'];

$tmp = $_FILES['image']['tmp_name'];

move_uploaded_file($tmp,"../../uploads/donations/".$filename);

$image = $filename;

}


/* INSERT */

mysqli_query($conn,"INSERT INTO donation_categories
(district_id,block_id,village_id,work_name,image,target_amount,status)
VALUES
('$district_id','$block_id','$village_id','$work_name','$image','$target','$status')
");

echo "<script>alert('Donation Work Added Successfully');</script>";

}

include "../layout/header.php";
include "../layout/sidebar.php";

?>

<div class="main">

<h2>Add Donation Work</h2>

<div class="form-box">

<form method="POST" enctype="multipart/form-data">

<label>Select District</label>

<select name="district_id" id="district" required>

<option value="">Select District</option>

<?php while($d=mysqli_fetch_assoc($districts)){ ?>

<option value="<?php echo $d['id']; ?>">
<?php echo $d['district_name']; ?>
</option>

<?php } ?>

</select>


<label>Select Block</label>

<select name="block_id" id="block" required>

<option value="">Select Block</option>

</select>


<label>Select Village</label>

<select name="village_id" id="village" required>

<option value="">Select Village</option>

</select>


<label>Work Name</label>

<input type="text" name="work_name" required>


<label>Target Amount</label>

<input type="number" name="target_amount" required>


<label>Upload Image</label>

<input type="file" name="image">


<label>Status</label>

<select name="status">

<option value="in_progress">Work In Progress</option>
<option value="completed">Completed</option>

</select>


<button type="submit" name="save" class="btn-save">

Save Work

</button>

</form>

</div>

</div>


<script>

/* LOAD BLOCKS */

document.getElementById("district").addEventListener("change", function(){

var district_id = this.value;

fetch("../villages/get_blocks.php?district_id="+district_id)

.then(response => response.text())

.then(data => {

document.getElementById("block").innerHTML = data;

});

});


/* LOAD VILLAGES */

document.getElementById("block").addEventListener("change", function(){

var block_id = this.value;

fetch("../villages/get_villages.php?block_id="+block_id)

.then(response => response.text())

.then(data => {

document.getElementById("village").innerHTML = data;

});

});

</script>

<?php include "../layout/footer.php"; ?>