<?php
// Include database connection
include("connection/conn.php");
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Initialize error message
$Error_msg = "";

// Fetch existing news data if ID is provided
$assoc = [];
if (!empty($_REQUEST['id'])) {
    $select = "SELECT * FROM currentnews_latest_tbl WHERE new_id='" . $_REQUEST['id'] . "'";
    $query = mysqli_query($link, $select);
    $assoc = mysqli_fetch_assoc($query);
}

// Handle form submission
if (isset($_POST['submit'])) {
    $news_title = mysqli_real_escape_string($link, trim($_POST['news_title'] ?? ''));
    $news_meta_key = mysqli_real_escape_string($link, trim($_POST['news_meta_key'] ?? ''));
    
    $news_meta_des = mysqli_real_escape_string($link, trim($_POST['news_meta_des'] ?? ''));
    $description = addslashes($_POST['description']);
    $newInfo = addslashes($_POST['newInfo']);
    $category = mysqli_real_escape_string($link, trim($_POST['category'] ?? ''));
    $status = isset($_POST['status']) ? 1 : 0;
   

    // Handle removed images
    $removed_images = isset($_POST['removed_images']) ? json_decode($_POST['removed_images'], true) : [];

    // Ensure $removed_images is an array (in case it's null)
    if (!is_array($removed_images)) {
        $removed_images = [];
    }

    // Handle existing images
    if (!empty($assoc['images'])) {
        $existing_images = json_decode($assoc['images'], true);
        // Ensure $existing_images is an array (in case it's null)
        if (!is_array($existing_images)) {
            $existing_images = [];
        }
        // Remove images that were deleted from the UI
        $updated_images = array_diff($existing_images, $removed_images);
    } else {
        $updated_images = [];
    }

    // Handle multiple image uploads
    $target_directory = "../listblg/";

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

    if (!empty($_FILES['images']['name'][0])) { // Check if at least one file is uploaded
        foreach ($_FILES['images']['name'] as $key => $name) {
            $file_ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
            $new_file_name = date('Ymd_His') . uniqid() . '.' . $file_ext;
            $upload_path_img = $_FILES['images']['tmp_name'][$key];
            $target_file = $target_directory . $new_file_name;

            if (in_array($file_ext, ['jpg', 'jpeg', 'png', 'gif'])) {
                if (move_uploaded_file($upload_path_img, $target_file)) {
                    $updated_images[] = $new_file_name; // Add new images to the list
                } else {
                    $Error_msg .= "Failed to upload the image: $name. Please check directory permissions.<br>";
                }
            } else {
                $Error_msg .= "Invalid file format for image: $name. Only jpg, jpeg, png, gif are allowed.<br>";
            }
        }
    }

    // Convert images array to JSON
    $uploaded_images_str = json_encode(array_values($updated_images));

    if (empty($Error_msg)) {
        if (!empty($_REQUEST['id'])) {
            $updateQuery = "UPDATE currentnews_latest_tbl SET 
                            news_title = '$news_title',
                            news_meta_key = '$news_meta_key',
                            news_meta_des = '$news_meta_des',
                            description = '$description',
                            newInfo = '$newInfo',
                            category = '$category',
                            images = '$uploaded_images_str'
                            WHERE new_id = '" . $_REQUEST['id'] . "'";

            mysqli_query($link, $updateQuery);
            header("Location: manage-news.php?success=News has been updated successfully.");
        } else {
            $insertRecords = "INSERT INTO currentnews_latest_tbl (news_title, news_meta_key,news_meta_des, description, newInfo, category, images) 
                              VALUES ('$news_title', '$news_meta_key', '$mo', '$m', '$news_meta_des', '$description', '$newInfo', '$category', '$uploaded_images_str')";

            mysqli_query($link, $insertRecords);
            header("Location: manage-news.php?success=News has been submitted successfully.");
        }
        exit();
    }
}

// Fetch categories
$sql = "SELECT id, course FROM course_category ORDER BY id ASC";
$result = mysqli_query($link, $sql);
?>


<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Administrator</title>
		<link href="css/bootstrap.css" rel="stylesheet" />
		<link href="css/style.css" rel="stylesheet" />
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
		
	<script src="vendors/modernizr-2.6.2-respond-1.1.0.min.js"></script>
	</head>
	
	<body>
		<div id="wrapper">
			<?php
				include("top-header.php");
				include("right-sec.php");
			?>
			<div id="page-wrapper" >
				<div id="page-inner">
					<div class="row">
						<div class="col-md-12">
							<h3 class="page-header">
								Update Course  <small></small>
							</h3>
							<div class="table-sec">
								<div class="srch_box">
									<form name="pnews" method="post" action="" enctype="multipart/form-data">
                                <div class="row">
                                    
                               
                                 <!-- Category -->
                                    <div class="col-md-12 col-xs-6">
                                        <div class="form-group form-select">
                                            <label>Class Category <span>*</span></label>
                                            <select name="category" id="course_category" class="form-control">
                                               <?php
                            $sqlcourse="SELECT * FROM course_category ORDER BY id ASC";
                            $resultcourse=mysqli_query($link,$sqlcourse);
                            while($findcourse=mysqli_fetch_array($resultcourse)){ ?>
                                <option value="<?php echo $findcourse['id']; ?>"><?php echo $findcourse['course']; ?></option>
                            <?php } ?>
                                               
                                            </select>
                    
                                        </div>
                                    </div>
                                     <div class="col-md-12 col-xs-6">    
                                    <div class="form-group form-select">
                                        <label>course name <span>*</span></label>
                                        <input class="form-control" type="text" name="news_title"  value="<?php echo $assoc['news_title'] ?? ''; ?>">
                                    </div>        
                                </div>    
                                <div class="col-md-12">
                                    <label>Meta Keyword <span>*</span></label>
                                    <textarea name="news_meta_key" required><?php echo $assoc['news_meta_key'] ?? ''; ?></textarea>
                                </div>
                               
                                <div class="col-md-12">
                                    <label>Meta Description <span>*</span></label>
                                    <textarea name="news_meta_des" ><?php echo $assoc['news_meta_des'] ?? ''; ?></textarea>
                                </div>
                                <div class="col-md-12">
                                    <label>Short Info <span>*</span></label>
                                    <textarea name="newInfo" id="ckeditor_full" ><?php echo $assoc['newInfo'] ?? ''; ?></textarea>
                                </div>
                                <div class="col-md-12 col-xs-6">	
                                <div class="form-group form-select">
                                <label>Description<span>*</span></label>
                                <textarea name="description"  rows="5" cols="10" id="ckeditor_full" ><?php echo $assoc['description'];?></textarea>
                                </div>		
                                </div>
                              
    
       
        <div class="col-md-12">
            <label>Image</label>
            <input type="file" name="img">
            <?php if (!empty($assoc['img'])): ?>
                <img src="../listblg/<?php echo $assoc['img']; ?>" height="50">
            <?php endif; ?>
        </div>
        <!-- HTML Form -->
<!-- HTML FORM -->
<div class="col-md-12">
    <label>Images</label>
    <input type="file" name="images[]" multiple>

    <div id="image-preview">
        <?php 
        if (!empty($assoc['images'])): 
            $imageList = json_decode($assoc['images'], true);
            foreach ($imageList as $index => $image): ?>
                <div id="image_<?php echo $index; ?>" style="display: inline-block; position: relative; margin-right: 10px;">
                    <img src="../listblg/<?php echo $image; ?>" height="50" style="border: 1px solid #ccc; padding: 5px;">
                    <span onclick="removeImage(<?php echo $index; ?>, '<?php echo $image; ?>')" 
                          style="position: absolute; top: -5px; right: -5px; background: red; color: white; 
                                 border-radius: 50%; cursor: pointer; padding: 3px 6px; font-size: 14px;">
                        ❌
                    </span>
                    <input type="hidden" name="existing_images[]" value="<?php echo $image; ?>">
                </div>
        <?php endforeach; endif; ?>
    </div>
</div>

<input type="hidden" name="removed_images" id="removedImages">

        <div class="col-md-12">
            <button type="submit" name="submit">Submit</button>
        </div>
    </div>
</form>
								</div>
							</div>
						</div>
					</div> 
				</div>
			</div>
			<div style="height:70px; clear:both">&nbsp;</div>
			<footer class="footer-sec">
				<div class="container">
					<div class="row">
						<div class="col-md-12">
							<p class="text-center">All right reserved. Template Design by: <a href="">Anshul Chittouria</a></p>
						</div>
					</div>
				</div>
			</footer>
		</div>
		
<!-- jQuery Js -->
		<script src="js/jquery-1.10.2.js"></script>
		<script src="js/bootstrap.min.js"></script>
		<script src="js/jquery.metisMenu.js"></script>
		<script src="js/custom-scripts.js"></script>
		<script src="vendors/jquery.validate.js" type="text/javascript"></script>
<script src="vendors/cms.js" type="text/javascript"></script>
<!--/.fluid-container-->
<link href="vendors/datepicker.css" rel="stylesheet" media="screen">
<link href="vendors/uniform.default.css" rel="stylesheet" media="screen">
<link href="vendors/chosen.min.css" rel="stylesheet" media="screen">
<link href="vendors/wysiwyg/bootstrap-wysihtml5.css" rel="stylesheet" media="screen">
<s<script src="vendors/wysiwyg/wysihtml5-0.3.0.js"></script>
<script src="vendors/wysiwyg/bootstrap-wysihtml5.js"></script>
<script src="vendors/wizard/jquery.bootstrap.wizard.min.js"></script>
<script src="assets/scripts.js"></script>
<script src="vendors/ckeditor/ckeditor.js"></script>
<script src="vendors/ckeditor/adapters/jquery.js"></script>
<script>
function removeImage(index, imageName) {
    document.getElementById('image_' + index).remove();

    let removedImagesInput = document.getElementById('removedImages');
    if (!removedImagesInput) {
        removedImagesInput = document.createElement('input');
        removedImagesInput.type = 'hidden';
        removedImagesInput.name = 'removed_images';
        removedImagesInput.id = 'removedImages';
        document.forms[0].appendChild(removedImagesInput);
    }

    let removedImages = removedImagesInput.value ? JSON.parse(removedImagesInput.value) : [];
    removedImages.push(imageName);
    removedImagesInput.value = JSON.stringify(removedImages);
}
</script>

<script>
$(function() {
    // Initialize CKEditor for the standard configuration
    $('textarea#ckeditor_standard').ckeditor({
        width: '98%',
        height: '150px',
        extraPlugins: 'pastefromword', // Enable PasteFromWord plugin
        toolbar: [
            { name: 'document', items: [ 'Source', '-', 'NewPage', 'Preview', '-', 'Templates' ] },
            [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ],
            { name: 'basicstyles', items: [ 'Bold', 'Italic' ] }
        ],
        allowedContent: true // Allow full HTML to improve pasted content handling
    });

    // Initialize CKEditor for the full configuration
    $('textarea#ckeditor_full').ckeditor({
        width: '98%',
        height: '150px',
        extraPlugins: 'pastefromword', // Enable PasteFromWord plugin
        toolbar: [
            { name: 'clipboard', items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
            { name: 'editing', items: [ 'Find', 'Replace', '-', 'SelectAll' ] },
            { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
        ],
        allowedContent: true // Allow full HTML to improve pasted content handling
    });
});
</script>
	</body>
</html>
