<?php
include "../../config/master.php";
allowRoles([1,5]);
include "../layout/header.php";

$role_id = $_SESSION['role_id'] ?? 0;

// DEFAULT VALUES
$district_id = "";
$block_id = "";
$village_id = "";

// SAVE NEWS
if(isset($_POST['save'])){

    // SAFE INPUT
    $title       = mysqli_real_escape_string($conn, $_POST['title'] ?? '');
    $news_date   = $_POST['news_date'] ?? '';
    $description = mysqli_real_escape_string($conn, $_POST['description'] ?? '');

    // ROLE BASE CONTROL
    if($role_id == 1){
        $district_id = $_POST['district_id'] ?? NULL;
        $block_id    = $_POST['block_id'] ?? NULL;
        $village_id  = $_POST['village_id'] ?? NULL;
    }else{
        $district_id = $_SESSION['district_id'] ?? NULL;
        $block_id    = $_SESSION['block_id'] ?? NULL;
        $village_id  = $_SESSION['village_id'] ?? NULL;
    }

    // IMAGE UPLOAD
    $image = "";

    if(isset($_FILES['image']) && $_FILES['image']['name'] != ""){

        $target_dir = "../../uploads/news/";

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

        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $image = "news_" . time() . rand(100,999) . "." . $ext;

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

    // INSERT QUERY
    $insert = mysqli_query($conn,"
        INSERT INTO village_news
        (district_id,block_id,village_id,title,news_date,image,description)
        VALUES
        ('$district_id','$block_id','$village_id','$title','$news_date','$image','$description')
    ");

    if($insert){
        echo "<script>alert('News Added Successfully');window.location='news_list.php';</script>";
        exit;
    }else{
        echo "<div style='color:red;'>Error: ".mysqli_error($conn)."</div>";
    }
}
?>

<div class="main">
<div class="container-fluid">

<div class="card-box">

<h3 style="margin-bottom:15px;">📰 Add News</h3>

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

<?php if($role_id == 1){ ?>

<label>District</label>
<select name="district_id" id="district" class="form-control" required>
<option value="">Select District</option>

<?php
$dq = mysqli_query($conn,"SELECT * FROM districts ORDER BY district_name ASC");
while($d = mysqli_fetch_assoc($dq)){
?>
<option value="<?php echo $d['id']; ?>">
<?php echo $d['district_name']; ?>
</option>
<?php } ?>

</select>

<br>

<label>Block</label>
<select name="block_id" id="block" class="form-control">
<option value="">Select Block</option>
</select>

<br>

<label>Village</label>
<select name="village_id" id="village" class="form-control">
<option value="">Select Village</option>
</select>

<br>

<?php } ?>

<label>News Title</label>
<input type="text" name="title" class="form-control" required>

<br>

<label>News Date</label>
<input type="date" name="news_date" class="form-control">

<br>

<label>Upload Image</label>
<input type="file" name="image" id="imageInput" class="form-control">

<img id="preview" style="width:100%;max-height:200px;margin-top:10px;display:none;border-radius:10px;">

<br>

<label>Description</label>
<textarea name="description" class="form-control" rows="4"></textarea>

<br>

<button type="submit" name="save" class="btn btn-success">Save News</button>

</form>

</div>
</div>
</div>

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

<script>

// DISTRICT → BLOCK
let district = document.getElementById("district");
if(district){
district.addEventListener("change", function(){

    fetch("get_blocks.php?district_id="+this.value)
    .then(res=>res.text())
    .then(data=>{
        document.getElementById("block").innerHTML = data;
        document.getElementById("village").innerHTML = "<option>Select Village</option>";
    });

});
}

// BLOCK → VILLAGE
let block = document.getElementById("block");
if(block){
block.addEventListener("change", function(){

    fetch("get_villages.php?block_id="+this.value)
    .then(res=>res.text())
    .then(data=>{
        document.getElementById("village").innerHTML = data;
    });

});
}

// IMAGE PREVIEW
let imageInput = document.getElementById("imageInput");
if(imageInput){
imageInput.addEventListener("change", function(e){

    let file = e.target.files[0];

    if(file){
        let reader = new FileReader();

        reader.onload = function(e){
            let img = document.getElementById("preview");
            img.src = e.target.result;
            img.style.display = "block";
        };

        reader.readAsDataURL(file);
    }

});
}

</script>