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

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

/* GET ID */
$id = intval($_GET['id']);

/* FETCH DATA */
$data = mysqli_fetch_assoc(mysqli_query($conn,"
SELECT * FROM special_thanks WHERE id='$id'
"));

if(!$data){
    echo "Invalid ID";
    exit;
}

/* UPDATE */

if(isset($_POST['update']))
{
    $name = mysqli_real_escape_string($conn,$_POST['name']);
    $designation = mysqli_real_escape_string($conn,$_POST['designation']);
    $description = mysqli_real_escape_string($conn,$_POST['description']);

    $image = $data['image'];

    /* IMAGE UPDATE */
    if(!empty($_FILES['image']['name']))
    {
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $new_image = time().".".$ext;

        if(move_uploaded_file(
            $_FILES['image']['tmp_name'],
            "../../uploads/special_thanks/".$new_image
        )){
            // delete old image
            if($image && file_exists("../../uploads/special_thanks/".$image)){
                unlink("../../uploads/special_thanks/".$image);
            }

            $image = $new_image;
        }
    }

    $update = mysqli_query($conn,"UPDATE special_thanks SET
    name='$name',
    designation='$designation',
    description='$description',
    image='$image'
    WHERE id='$id'
    ");

    if($update){
        echo "<script>alert('Updated Successfully');window.location='special_thanks_list.php';</script>";
    }else{
        echo "<script>alert('Error');</script>";
    }
}
?>

<div class="main">

<h2>Edit Special Thanks</h2>

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

<label>Name</label>
<input type="text" name="name" value="<?php echo $data['name']; ?>" required>

<label>Designation</label>
<input type="text" name="designation" value="<?php echo $data['designation']; ?>">

<label>Current Image</label><br>

<?php if($data['image']){ ?>
<img src="../../uploads/special_thanks/<?php echo $data['image']; ?>" width="120" style="margin-bottom:10px;">
<?php } ?>

<label>Change Image</label>
<input type="file" name="image">

<label>Description</label>
<textarea name="description" id="editor"><?php echo $data['description']; ?></textarea>

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

</form>

</div>

<!-- CKEDITOR -->
<script src="https://cdn.ckeditor.com/4.22.1/standard/ckeditor.js"></script>
<script>
CKEDITOR.replace('editor');
</script>

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