<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include database connection
include("connection/conn.php");

// Initialize error message
$Error_msg = "";

// Handle form submission
if (isset($_POST['submit'])) {
    // Escape and sanitize input data
    $news_title = mysqli_real_escape_string($link, trim($_POST['news_title'] ?? ''));
    $subject = mysqli_real_escape_string($link, trim($_POST['subject'] ?? ''));
    $news_meta_key = mysqli_real_escape_string($link, trim($_POST['news_meta_key'] ?? ''));
    $mo = mysqli_real_escape_string($link, trim($_POST['mo'] ?? ''));
    $m = mysqli_real_escape_string($link, trim($_POST['m'] ?? ''));
    $news_meta_des = mysqli_real_escape_string($link, trim($_POST['news_meta_des'] ?? ''));
    $Quarterly = mysqli_real_escape_string($link, trim($_POST['Quarterly'] ?? ''));
    $monthly_course_fee = mysqli_real_escape_string($link, trim($_POST['monthly_course_fee'] ?? ''));
    $duration = mysqli_real_escape_string($link, trim($_POST['duration'] ?? ''));
    $video_link = mysqli_real_escape_string($link, trim($_POST['video_link'] ?? ''));
    $course_mode = mysqli_real_escape_string($link, trim($_POST['course_mode'] ?? ''));
    $description = mysqli_real_escape_string($link, trim($_POST['description'] ?? ''));
    $newInfo = mysqli_real_escape_string($link, trim($_POST['newInfo'] ?? ''));
    $features = mysqli_real_escape_string($link, trim($_POST['features'] ?? ''));
    $standers = mysqli_real_escape_string($link, trim($_POST['standers'] ?? ''));
    $specifications = mysqli_real_escape_string($link, trim($_POST['specifications'] ?? ''));
    $product = mysqli_real_escape_string($link, trim($_POST['prduct'] ?? ''));
    $category = mysqli_real_escape_string($link, trim($_POST['category'] ?? ''));
    $status = isset($_POST['status']) ? 1 : 0;

    // Validate required fields
    if (empty($news_title)) {
        $Error_msg .= "Please enter the title.<br>";
    }

    // Directory for uploads
    $target_directory = "../listblg/";
    if (!is_dir($target_directory) && !mkdir($target_directory, 0777, true)) {
        $Error_msg .= "Failed to create the directory for image uploads.<br>";
    }

    // Handle single image upload
    $img = "default-image.jpg"; // Default image
    if (!empty($_FILES['img']['name'])) {
        $file_ext = strtolower(pathinfo($_FILES['img']['name'], PATHINFO_EXTENSION));
        $img = date('Ymd_His') . uniqid() . '.' . $file_ext;
        $target_file = $target_directory . $img;

        if (in_array($file_ext, ['jpg', 'jpeg', 'png', 'gif'])) {
            if (!move_uploaded_file($_FILES['img']['tmp_name'], $target_file)) {
                $Error_msg .= "Failed to upload the image.<br>";
            }
        } else {
            $Error_msg .= "Invalid file format for image.<br>";
        }
    }

    // Handle multiple image uploads
    $uploaded_images = [];
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['name'] as $key => $name) {
            $file_ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
            $new_file_name = date('Ymd_His') . uniqid() . '.' . $file_ext;
            $target_file = $target_directory . $new_file_name;

            if (in_array($file_ext, ['jpg', 'jpeg', 'png', 'gif'])) {
                if (move_uploaded_file($_FILES['images']['tmp_name'][$key], $target_file)) {
                    $uploaded_images[] = $new_file_name;
                } else {
                    $Error_msg .= "Failed to upload the image: $name.<br>";
                }
            } else {
                $Error_msg .= "Invalid file format for image: $name.<br>";
            }
        }
    }
    $uploaded_images_str = json_encode($uploaded_images);

    // Insert data into the database
    if (empty($Error_msg)) {
        $insertRecords = "INSERT INTO currentnews_latest_tbl (
            news_title, news_meta_key, subject, m, mo, news_meta_des, Quarterly, 
            monthly_course_fee, duration, video_link, course_mode, description, 
            newInfo, features, standers, specifications, prduct, 
            category, img, images, status
        ) VALUES (
            '$news_title', '$news_meta_key', '$subject', '$mo', '$m', '$news_meta_des', 
            '$Quarterly', '$monthly_course_fee', '$duration', '$video_link', 
            '$course_mode', '$description', '$newInfo', '$features', '$standers', 
            '$specifications', '$product', '$category', '$img', '$uploaded_images_str', '$status'
        )";

        if (mysqli_query($link, $insertRecords)) {
            header("Location: manage-news.php?success=News has been submitted successfully.");
            exit();
        } else {
            $Error_msg .= "Error in submitting news: " . mysqli_error($link) . "<br>";
        }
    }
}

// Fetch categories
$sql = "SELECT id, course FROM course_category ORDER BY id ASC";
$result = mysqli_query($link, $sql);
if (!$result) {
    die("Query failed: " . mysqli_error($link));
}
?>




<!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">
								Add Course  <small></small>
							</h3>
							<div class="table-sec">
								<div class="srch_box">
									<form name="pnews" id="pnews" method="post" action="" enctype="multipart/form-data">
    <div class="row">
        <div class="col-md-12 col-xs-12">
            <div class="pnl_box"> 
              <!-- Category -->
                <div class="col-md-12 col-xs-6">
                    <div class="form-group form-select">
                        <label>Course Category <span>*</span></label>
                        <select name="category" id="course_category" class="form-control">
                            <option value="Course">Course Category</option>
                            <?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" >
                    </div>        
                </div>
                
              
                <div class="col-md-12 col-xs-6">
                    <div class="form-group form-select">
                        <label>Meta Keyword <span>*</span></label>
                        <textarea class="form-control" name="news_meta_key" ></textarea>
                    </div>        
                </div>
                
                <div class="col-md-12 col-xs-6">
                    <div class="form-group form-select">
                        <label>Meta Description <span>*</span></label>
                        <textarea class="form-control" name="news_meta_des" ></textarea>
                    </div>        
                </div>
                
               
                <div class="col-md-12 col-xs-6">	
                    <div class="form-group form-select">
                        <label>Short Info<span>*</span></label>
                        <textarea name="newInfo" rows="5" cols="10" id="ckeditor_full" ></textarea>
                        
                        
                    </div>		
                </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" ></textarea>
                    </div>		
                </div>
                 
              
                
                <div class="col-md-12 col-xs-6">    
                    <div class="form-group form-select">
                        <label>Image <span>*</span></label>
                        <input class="form-control" type="file" name="img" >
                    </div>        
                </div>
                <div class="col-md-12 col-xs-6">
              <div class="form-group" style="margin-bottom: 20px;">
            <label for="images">Multiple Images:</label>
            <input 
                type="file" 
                name="images[]" 
                id="images" 
                class="form-control" 
                multiple 
                onchange="handleImageSelection(event)" 
                style="display: block; margin-top: 10px;"
            >
        </div>
        <div 
            id="imagePreviewContainer" 
            style="display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px;"
        ></div>

    </div>

            </div>    
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 col-xs-4">    
            <div class="btn_sec">
                <input type="submit" name="submit" value="Submit" />
            </div>
        </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="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $('#course_category').change(function(){
        var course_id = $(this).val();
        if(course_id != ''){
            $.ajax({
                url: "fetch_subjects.php",
                method: "POST",
                data: {course_id: course_id},
                success: function(data){
                    $('#subject').html(data);
                }
            });
        } else {
            $('#subject').html('<option value="">Select Subject</option>');
        }
    });
});
</script>
		<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>
        const imagesArray = []; // Array to store uploaded images

        function handleImageSelection(event) {
            const files = event.target.files;
            const previewContainer = document.getElementById('imagePreviewContainer');

            // Loop through the selected files
            Array.from(files).forEach((file) => {
                if (file.type.startsWith('image/')) {
                    imagesArray.push(file); // Add the image file to the array

                    // Create a preview for the image
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const previewDiv = document.createElement('div');
                        previewDiv.setAttribute(
                            'style', 
                            'position: relative; width: 100px; height: 100px;'
                        );

                        const img = document.createElement('img');
                        img.src = e.target.result;
                        img.setAttribute(
                            'style', 
                            'width: 100%; height: 100%; object-fit: cover; border: 1px solid #ccc; border-radius: 5px;'
                        );

                        const closeButton = document.createElement('span');
                        closeButton.innerHTML = '&times;';
                        closeButton.setAttribute(
                            'style', 
                            'position: absolute; top: -5px; right: -5px; background: red; color: white; border-radius: 50%; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 16px;'
                        );

                        // Add click event to remove the image
                        closeButton.addEventListener('click', () => {
                            const index = imagesArray.indexOf(file); // Find file index
                            if (index !== -1) imagesArray.splice(index, 1); // Remove file from the array
                            previewDiv.remove(); // Remove the preview div
                        });

                        previewDiv.appendChild(img);
                        previewDiv.appendChild(closeButton);
                        previewContainer.appendChild(previewDiv);
                    };
                    reader.readAsDataURL(file);
                } else {
                    alert('Only image files are allowed.');
                }
            });
        }
    </script>

<script>
$(function() {
    // Initialize CKEditor for the standard configuration
    $('textarea#ckeditor_standard').ckeditor({
        width: '98%',
        height: '100%',
        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>
