FIX_Advertise Image Changes

This commit is contained in:
sanjeev.p 2025-12-11 14:27:53 +05:30
parent 0a6a225f5d
commit 4cf762ca9c
3 changed files with 343 additions and 179 deletions

View File

@ -52,10 +52,11 @@ $routes->get("importRules", "RuleImportController::upload");
// $routes->post("employeeUpload", "EmployeeRestController::employeeUpload");
$routes->post("add_advertise_image", "AppContentManagementController::add_advertise_image");
$routes->post('remove_advertise_image', 'AppContentManagementController::remove_advertise_image');
$routes->get("add_image_index", "AppContentManagementController::add_image_index");
$routes->get("getAdvertiseImage/(:any)", "AppContentManagementController::getAdvertiseImage/$1");
$routes->get("frontend_content", "AppContentManagementController::frontend_content");
$routes->get('showAdvertiseImage/(:any)', 'AdvertiseController::showAdvertiseImage/$1');
$routes->get('showAdvertiseImage/(:any)', 'AppContentManagementController::showAdvertiseImage/$1');
// $routes->get('/', 'LoginController::index');

View File

@ -10,6 +10,7 @@ use CodeIgniter\API\ResponseTrait;
use App\Models\AddImgModel;
use App\Models\FEContentModel;
use App\Models\ClientModel;
class AppContentManagementController extends AdminController
{
@ -17,19 +18,31 @@ class AppContentManagementController extends AdminController
protected $myLogger;
protected $addImgModel;
protected $feContentModel;
protected $clientModel;
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
$this->addImgModel = new AddImgModel();
$this->addImgModel = new AddImgModel();
$this->feContentModel = new FEContentModel();
$this->clientModel = new ClientModel();
}
public function add_image_index()
{
$this->myLogger->logme('error','Addvertisement Image list function called');
$headerData['tab_name'] = 'Addvertisement Images';
$headerData['page_name'] = 'Addvertisement Images';
$data['addImageList'] = $this->addImgModel->findAll();
// $data['addImageList'] = $this->addImgModel->findAll();
$data['addImageList'] = $this->addImgModel->select('advertisement_images.*,
clients.client_name,
clients.short_name,
CASE WHEN advertisement_images.is_active = 1 THEN "Active" ELSE "Inactive" END AS status', false)
->join('clients', 'advertisement_images.client_id = clients.id', 'left')
->where('advertisement_images.is_active', 1)
->findAll();
$data['client'] = $this->clientModel->where('is_active', 1)->findAll();
// dd($data);
@ -40,12 +53,14 @@ class AppContentManagementController extends AdminController
// $this->loadLayout('client_onboarding', $data);
}
// using add and edit
public function add_advertise_image() {
try {
$file = $this->request->getFile('advertise_image');
$client_id = $this->request->getPost('client_id');
//1) original file name for vaildations
$fileName = $file->getClientName(); //original file name for vaildations
$existing = $this->addImgModel->where('name', $fileName)->where('is_active', 1)->first();
$existing = $this->addImgModel->where('name', $fileName)->where('client_id', $fileName)->where('is_active', 1)->first();
if($existing){ return $this->respond(['status' => false, 'message' => 'This file has already been uploaded in active state.'], 400); }
//skip 1) and use this
@ -62,7 +77,7 @@ class AppContentManagementController extends AdminController
$file->move($uploadPath, $fileName);
$id = $this->request->getPost('add_image_id');
$data = ['name' => $fileName];
$data = ['name' => $fileName,'client_id'=>$client_id];
if ($id == 0) {
$this->addImgModel->insert($data);
@ -76,22 +91,57 @@ class AppContentManagementController extends AdminController
}
}
public function showAdvertiseImage($fileName)
public function remove_advertise_image()
{
try {
$id = $this->request->getPost('add_image_id');
$filePath = WRITEPATH . 'uploads/advertiseImage/' . $fileName;
if (!$id) {
return $this->respond(['status' => false, 'message' => 'ID missing'], 400);
}
if (!file_exists($filePath)) {
return $this->response->setStatusCode(404, 'File not found');
$data = ['is_active' => 0];
$this->addImgModel->update($id, $data);
return $this->respond(['status' => true, 'message' => 'Deleted successfully']);
} catch (\Exception $e) {
return $this->respond(['status' => false, 'message' => $e->getMessage()], 500);
}
}
// public function showAdvertiseImage($fileName)
// {
// $filePath = WRITEPATH . 'uploads/advertiseImage/' . $fileName;
// if (!file_exists($filePath)) {
// return $this->response->setStatusCode(404, 'File not found');
// }
// $mimeType = mime_content_type($filePath);
// header('Content-Type: ' . $mimeType);
// readfile($filePath);
// exit;
// }
// In AppContentManagementController.php (This is what needs to be fixed if the direct path fails)
public function showAdvertiseImage($filename)
{
$path = WRITEPATH . 'uploads/advertiseImage/' . $filename;
if (!file_exists($path)) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
$mimeType = mime_content_type($filePath);
header('Content-Type: ' . $mimeType);
readfile($filePath);
exit;
$mime = mime_content_type($path);
return $this->response->setHeader('Content-Type', $mime)->setBody(file_get_contents($path));
}
public function getAdvertiseImage($image_id){
$image_data = $this->addImgModel->select('name')->where(['id' => $image_id])->first();

View File

@ -40,6 +40,8 @@ table.dataTable thead th {
<thead class="bg-light">
<tr>
<th class="font-weight-medium"><div class="column-header">Advertisement Image Name</div></th>
<th class="font-weight-medium"><div class="column-header">Client Name</div></th>
<th class="font-weight-medium"><div class="column-header">Client Short Name</div></th>
<th class="font-weight-medium"><div class="column-header">Status</div></th>
<th class="font-weight-medium"><div class="column-header">Action</div></th>
</tr>
@ -49,19 +51,18 @@ table.dataTable thead th {
<?php foreach($addImageList as $row){ ?>
<tr >
<td class="client_info" data-id="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></td>
<td class="client_info" ><?php echo $row['client_name']; ?></td>
<td class="client_info" ><?php echo $row['short_name']; ?></td>
<td class="client_info" ><?php echo $row['status']; ?></td>
<td>
<?php echo $row['is_active']; ?>
</td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item advertise_image_edit" href="#" data-toggle="modal" data-id="<?php echo $row['id']; ?>" data-name="<?php echo $row['name']; ?>" data-target="#bike_make_login-modal"><i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
<a class="dropdown-item" data-id="<?= $row['id'];?>" onclick="removeClient(this)"><i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete</a>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown"aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item advertise_image_edit" href="#" data-toggle="modal" data-wholearray='<?php echo json_encode($row, JSON_HEX_APOS); ?>' data-target="#bike_make_login-modal"><i class="mdi mdi-pencil mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
<a class="dropdown-item" onclick="remove_advertise_image('<?= $row['id'];?>')"><i class="mdi mdi-delete mr-2 text-muted font-18 vertical-middle"></i>Delete</a>
</div>
</div>
</div>
</td>
</tr>
<?php } ?>
@ -88,6 +89,7 @@ table.dataTable thead th {
<form id="model_form_data" class="px-4" enctype="multipart/form-data">
<input type="hidden" name="add_image_id" id="add_image_id" value="0">
<!-- old
<div class="row">
<div class="col-md-12">
<div class="form-group">
@ -100,8 +102,63 @@ table.dataTable thead th {
<div class="form-group col-md-6 float-left" style="position: relative;top: 0px;">
<img src=" " width="100" height="100" id="uploadPreview" class="avatar img-circle img-thumbnail" alt="avatar"/>
</div>
<div class="form-group col-md-3">
<label for="client_branch">Client<span class="text-danger">*</span></label>
<select class="form-control" id="client_id" name="client_id" required>
<option value="">Select Client</option>
<?php
if (isset($client) && count($client)) {
foreach ($client as $key => $value) {
echo "<option value='" . $value['id'] . "'>" . $value['client_name'] . "</option>";
}
}
?>
</select>
</div>
</div>
</div>
-->
<div class="row mb-2 align-items-stretch">
<!-- Left column: col-8 -->
<div class="col-md-8 d-flex flex-column justify-content-between">
<!-- Top section -->
<div class="form-group">
<label for="branchname">Upload Image</label>
<div class="input-icon">
<input type="file" class="form-control" name="advertise_image" id="advertise_image" accept="image/*" onchange="PreviewImage();" required>
<i class="mdi mdi-upload additional-icon"></i>
</div>
</div>
<!-- Bottom section -->
<div class="form-group">
<label for="client_branch">Client <span class="text-danger">*</span></label>
<select class="form-control" id="client_id" name="client_id" required>
<option value="">Select Client</option>
<?php
if (isset($client) && count($client)) {
foreach ($client as $value) {
echo "<option value='" . $value['id'] . "'>" . $value['client_name'] . "</option>";
}
}
?>
</select>
</div>
</div>
<!-- Right column: col-4, preview image -->
<div class="col-md-4 d-flex flex-column align-items-center justify-content-center">
<img src="" class="avatar img-circle img-thumbnail" id="uploadPreview" alt="Preview" style="max-width: 100%; height: auto;">
<small style="font-size: x-small; margin-top: 5px; text-align: center;">
dimensions - 1640x664 pixels <br> size - 200kb
</small>
</div>
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary" onclick="submitBranch()">Submit</button>
@ -116,158 +173,191 @@ table.dataTable thead th {
<script>
function submitBranch() {
const fileInput = $('#advertise_image')[0].files[0]; // get actual file object
const imageId = $('#add_image_id').val();
function submitBranch() {
const fileInput = $('#advertise_image')[0].files[0]; // get actual file object
const imageId = $('#add_image_id').val();
const clientId = $('#client_id').val();
if (!fileInput) {
toastr.warning('Please upload an image before submitting', 'Warning');
$('#advertise_image').focus();
return;
if (!fileInput) {
toastr.warning('Please upload an image before submitting', 'Warning');
$('#advertise_image').focus();
return;
}
if(!clientId){
toastr.warning('Please Select Client.', 'Warning');
$('#client_id').focus();
return;
}
var url = '<?= base_url("add_advertise_image") ?>';
var formData = new FormData();
formData.append('advertise_image', fileInput);
formData.append('add_image_id', imageId);
formData.append('client_id', clientId);
$.ajax({
type: 'POST',
url: url,
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function(response) {
console.log(response);
if (response.status) {
$('#bike_make_login-modal').modal('hide');
$('#advertise_image').val('');
$('#client_id').val('');
$('#uploadPreview').attr('src', '<?= base_url('public/assets/images/avatar_2x.png') ?>');
toastr.success('Image uploaded successfully!');
window.location.reload();
} else {
toastr.error(response.message || 'Something went wrong.');
}
},
error: function(xhr, status, error) {
console.error(xhr.responseText);
console.error('Status:', status);
console.error('Error:', error);
let msg = 'Something went wrong. Please try again later.';
switch (xhr.status) {
case 400:
msg = xhr.responseJSON?.message || 'Bad Request — Invalid input.';
break;
case 401:
msg = 'Unauthorized — Please log in again.';
break;
case 403:
msg = 'Forbidden — You do not have permission.';
break;
case 404:
msg = 'Not Found — Requested URL or resource not found.';
break;
case 500:
console.log('Internal Server Error — Please contact support.');
msg = xhr.responseJSON?.message || xhr.responseText || msg;
break;
default:
msg = xhr.responseJSON?.message || xhr.responseText || msg;
}
}
});
}
var url = '<?= base_url("add_advertise_image") ?>';
var formData = new FormData();
formData.append('advertise_image', fileInput);
formData.append('add_image_id', imageId);
function PreviewImage() {
console.log('function called');
var fileInput = document.getElementById("advertise_image");
var file = fileInput.files[0];
if (file) {
var allowedExtensions = ["jpg", "jpeg", "png"];
var fileExtension = file.name.split('.').pop().toLowerCase();
if (!allowedExtensions.includes(fileExtension) || file.size > 200 * 1024) {
toastr.warning('Maximum file size allowed is 200KB.', 'File size exceeds limit.');
fileInput.value = ""; // Clear the file input
document.getElementById("uploadPreview").src = "<?= base_url()."public/assets/images/avatar_2x.png" ?>"; // Remove the preview image
return;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
var img = new Image();
img.src = event.target.result;
img.onload = function () {
if (img.width !== 1640 || img.height !== 664) {
toastr.warning('Image dimensions must be 1640x664 pixels.', 'Invalid image dimensions.');
fileInput.value = ""; // Clear the file input
document.getElementById("uploadPreview").src = "<?= base_url()."public/assets/images/avatar_2x.png" ?>"; // Remove the preview image
} else {
document.getElementById("uploadPreview").src = img.src;
}
};
};
}
}
var table;
$(document).ready(function() {
$('#add_image_id').val('');
$('#client_id').val('');
$('#advertise_image').val('');
table = $('#tickets-table').DataTable({
// dom: "<'row'<'col-sm-1'f><'col-sm-11 text-right'B>>" + // Filter left, button right
// "<'row'<'col-sm-12'tr>>" +
// "<'row'<'col-sm-5'i><'col-sm-7'p>>",
dom: "<'row'<'col-12 d-flex justify-content-between align-items-center'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
text: '<i class="mdi mdi-plus"></i> <span class="btn-custom">Add</span>',
className: 'btn app-btn-primary',
action: function (e, dt, node, config) {
// ✅ Call your modal logic
callmodal();
}
}
],
language: {
search: `
<div class="datatable-search-wrapper" style="position:relative; display:inline-block;">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666;"></i>
<i class="mdi mdi-close-circle datatable-clear-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666; display:none;"></i>
</div>`,
searchPlaceholder: "Search",
emptyTable: '<div class="text-center text-muted">No Data found</div>'
},
paging: true
});
});
// ✅ Define your modal function separately
function callmodal() {
$('#add_image_id').val(0);
$('#advertise_add_edit').html('Add Advertise Image');
$('#uploadPreview').attr('src', '<?= base_url()."public/assets/images/avatar_2x.png" ?>');
$('#bike_model_login-modal').modal('show'); // ✅ this shows the modal
var myModal = new bootstrap.Modal(document.getElementById('bike_make_login-modal'));
myModal.show();
}
function remove_advertise_image(id) {
if (!confirm("Are you sure you want to delete this image?")) return;
$.ajax({
type: 'POST',
url: url,
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function(response) {
console.log(response);
if (response.status) {
$('#bike_make_login-modal').modal('hide');
$('#advertise_image').val('');
$('#uploadPreview').attr('src', '<?= base_url('public/assets/images/avatar_2x.png') ?>');
toastr.success('Image uploaded successfully!');
window.location.reload();
} else {
toastr.error(response.message || 'Something went wrong.');
}
url: '<?= base_url("remove_advertise_image"); ?>',
data: { add_image_id: id },
success: function (response) {
toastr.success('Deleted successfully');
location.reload(); // refresh page
},
error: function(xhr, status, error) {
error: function (xhr) {
console.error(xhr.responseText);
console.error('Status:', status);
console.error('Error:', error);
let msg = 'Something went wrong. Please try again later.';
switch (xhr.status) {
case 400:
msg = xhr.responseJSON?.message || 'Bad Request — Invalid input.';
break;
case 401:
msg = 'Unauthorized — Please log in again.';
break;
case 403:
msg = 'Forbidden — You do not have permission.';
break;
case 404:
msg = 'Not Found — Requested URL or resource not found.';
break;
case 500:
console.log('Internal Server Error — Please contact support.');
msg = xhr.responseJSON?.message || xhr.responseText || msg;
break;
default:
msg = xhr.responseJSON?.message || xhr.responseText || msg;
}
}
});
}
function PreviewImage() {
console.log('function called');
var fileInput = document.getElementById("advertise_image");
var file = fileInput.files[0];
if (file) {
var allowedExtensions = ["jpg", "jpeg", "png"];
var fileExtension = file.name.split('.').pop().toLowerCase();
if (!allowedExtensions.includes(fileExtension) || file.size > 200 * 1024) {
toastr.warning('Maximum file size allowed is 200KB.', 'File size exceeds limit.');
fileInput.value = ""; // Clear the file input
document.getElementById("uploadPreview").src = "<?= base_url()."public/assets/images/avatar_2x.png" ?>"; // Remove the preview image
return;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
var img = new Image();
img.src = event.target.result;
img.onload = function () {
if (img.width !== 1640 || img.height !== 664) {
toastr.warning('Image dimensions must be 1640x664 pixels.', 'Invalid image dimensions.');
fileInput.value = ""; // Clear the file input
document.getElementById("uploadPreview").src = "<?= base_url()."public/assets/images/avatar_2x.png" ?>"; // Remove the preview image
} else {
document.getElementById("uploadPreview").src = img.src;
}
};
};
}
}
var table;
$(document).ready(function() {
table = $('#tickets-table').DataTable({
// dom: "<'row'<'col-sm-1'f><'col-sm-11 text-right'B>>" + // Filter left, button right
// "<'row'<'col-sm-12'tr>>" +
// "<'row'<'col-sm-5'i><'col-sm-7'p>>",
dom: "<'row'<'col-12 d-flex justify-content-between align-items-center'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>",
lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]],
buttons: [
{
text: '<i class="mdi mdi-plus"></i> <span class="btn-custom">Add</span>',
className: 'btn app-btn-primary',
action: function (e, dt, node, config) {
// ✅ Call your modal logic
callmodal();
}
}
],
language: {
search: `
<div class="datatable-search-wrapper" style="position:relative; display:inline-block;">
_INPUT_
<i class="mdi mdi-magnify datatable-search-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666;"></i>
<i class="mdi mdi-close-circle datatable-clear-icon"
style="position:absolute; right:10px; top:50%; transform:translateY(-50%); color:#666; display:none;"></i>
</div>`,
searchPlaceholder: "Search",
emptyTable: '<div class="text-center text-muted">No Data found</div>'
},
paging: true
});
});
// ✅ Define your modal function separately
function callmodal() {
$('#add_image_id').val(0);
$('#advertise_add_edit').html('Add Advertise Image');
$('#uploadPreview').attr('src', '<?= base_url()."public/assets/images/avatar_2x.png" ?>');
$('#bike_model_login-modal').modal('show'); // ✅ this shows the modal
var myModal = new bootstrap.Modal(document.getElementById('bike_make_login-modal'));
myModal.show();
}
// $('#btnAdd').click(function () {
// $('#add_image_id').val(0);
// $('#advertise_add_edit').html('Add Advertise Image');
@ -299,28 +389,51 @@ function callmodal() {
// })
// })
$(document).on('click', '.advertise_image_edit', function (e) {
e.preventDefault();
e.preventDefault();
// 1. Clear fields first for a clean state (Good practice)
$('#add_image_id').val('');
$('#client_id').val('');
$('#advertise_image').val('');
// Reset preview to default before processing to avoid flicker/old image
$('#uploadPreview').attr('src', '<?= base_url("public/assets/images/avatar_2x.png") ?>');
let wholearray = JSON.parse($(this).attr('data-wholearray'));
let ad_name = wholearray.name;
let ad_id = wholearray.id;
let c_id = wholearray.client_id; // This holds the Client ID for the dropdown
console.log('Whole array:', wholearray);
console.log('Clicked ID:', c_id);
// 2. Set the data fields and title
$('#add_image_id').val(ad_id);
$('#advertise_add_edit').html('Edit Advertise Image');
// 🎯 CRITICAL FIX: Set the value of the Client SELECT dropdown
// This pre-selects the client associated with the image.
$('#client_id').val(c_id);
const id = $(this).data('id');
const name = $(this).data('name');
console.log('Clicked ID:', id);
console.log('<?= base_url(); ?>');
// 3. Construct the image URL
// NOTE: If this path fails (404/403), revert to the previous controller path:
const imgUrl = '<?= base_url("showAdvertiseImage/"); ?>' + ad_name;
// const imgUrl = '<?= base_url("writable/uploads/advertiseImage/"); ?>' + ad_name;
$('#add_image_id').val(id);
$('#advertise_image').val(name);
$('#advertise_add_edit').html('Edit Advertise Image');
const imgUrl = '<?= base_url("showAdvertiseImage/"); ?>' + name;
$('#uploadPreview').attr('src', imgUrl)
.on('error', function() {
$(this).attr('src', '<?= base_url()."public/assets/images/avatar_2x.png" ?>');
// 4. Set the image source AND add robust error handling for default image
$('#uploadPreview').attr('src', imgUrl).on('error', function() {
// Fallback: If the image fails to load, set the source to the default image.
$(this).attr('src', '<?= base_url("public/assets/images/avatar_2x.png") ?>');
});
// 5. Clear the file input
$('#advertise_image').val('');
// 6. Show the modal
var myModal = new bootstrap.Modal(document.getElementById('bike_make_login-modal'));
myModal.show();
});
});
</script>