<?php 
include ('includes/header.php');

//table name
$table_name = "ads";
//current file var

//create if not
$db->exec("CREATE TABLE IF NOT EXISTS {$table_name}(id INTEGER PRIMARY KEY  NOT NULL, title TEXT ,extension TEXT,createdon TEXT, path TEXT)");

//type call
$db->exec("CREATE TABLE IF NOT EXISTS type (id INTEGER PRIMARY KEY  NOT NULL, type TEXT)");

$rowsc = $db->query("SELECT COUNT(*) as count FROM type");
$rowc = $rowsc->fetchArray();
$numRows = $rowc['count'];
if ($numRows == 0){
	$db->exec("INSERT INTO type(type) VALUES('ua')");
}

$resT = $db->querySingle('SELECT type FROM type WHERE id=1');
//table call
$res = $db->query("SELECT * FROM {$table_name}");

//submit new
if (!file_exists($table_name)) {
	mkdir($table_name, 511, true);
}

if (isset($_POST['submit'])) {
	Submit('sub_new', $db, $table_name);
}

//sub type
if (isset($_POST['submit_type'])) {
		$db->exec("UPDATE type SET type='".sanitize($_POST['type_1'])."'");
		$db->close();
		echo "<script>window.location.href='adverts.php?status=2'</script>";
}
//delete row
if (isset($_GET['delete'])) {
	Submit('sub_del', $db, $table_name);
	echo "<script>window.location.href='adverts.php?status=3'</script>";
}

function Submit($sub_type, $db, $table_name){
	if ($sub_type == 'sub_new') {
		$upload_dir = 'ads/';
		if (!file_exists($upload_dir)) {
			mkdir($upload_dir, 0777, true);
		}

		if (!isset($_FILES['ad_image']) || $_FILES['ad_image']['error'] !== UPLOAD_ERR_OK) {
			echo "<script>alert('Please choose an advert file to upload.');window.location.href='adverts.php?create'</script>";
			$db->close();
			return;
		}

		$original_name = $_FILES['ad_image']['name'];
		$tmp_name = $_FILES['ad_image']['tmp_name'];
		$file_size = (int) $_FILES['ad_image']['size'];
		$file_ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
		$image_allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
		$video_allowed = ['mp4', 'webm'];
		$allowed = array_merge($image_allowed, $video_allowed);

		if (!in_array($file_ext, $allowed, true)) {
			echo "<script>alert('Only JPG, JPEG, PNG, GIF, WEBP, MP4, and WEBM files are allowed.');window.location.href='adverts.php?create'</script>";
			$db->close();
			return;
		}

		if ($file_size > 50 * 1024 * 1024) {
			echo "<script>alert('Advert file is too large. Max size is 50MB.');window.location.href='adverts.php?create'</script>";
			$db->close();
			return;
		}

		if (in_array($file_ext, $image_allowed, true)) {
			$image_info = @getimagesize($tmp_name);
			if ($image_info === false) {
				echo "<script>alert('Uploaded file is not a valid image.');window.location.href='adverts.php?create'</script>";
				$db->close();
				return;
			}
		} elseif (in_array($file_ext, $video_allowed, true)) {
			$finfo = finfo_open(FILEINFO_MIME_TYPE);
			$mime = $finfo ? finfo_file($finfo, $tmp_name) : '';
			if ($finfo) {
				finfo_close($finfo);
			}
			$valid_video_mimes = ['video/mp4', 'video/webm', 'application/octet-stream'];
			if (!in_array($mime, $valid_video_mimes, true)) {
				echo "<script>alert('Uploaded file is not a valid video.');window.location.href='adverts.php?create'</script>";
				$db->close();
				return;
			}
		}

		$safe_name = preg_replace('/[^A-Za-z0-9_-]/', '_', pathinfo($original_name, PATHINFO_FILENAME));
		if (empty($safe_name)) {
			$safe_name = 'advert';
		}
		$final_name = time() . '_' . $safe_name . '.' . $file_ext;
		$target_file = $upload_dir . $final_name;

		if (!move_uploaded_file($tmp_name, $target_file)) {
			echo "<script>alert('Upload failed. Please try again.');window.location.href='adverts.php?create'</script>";
			$db->close();
			return;
		}

		$db->exec("INSERT INTO {$table_name}(title ,extension,createdon, path) VALUES('".sanitize($_POST['title'])."','".sanitize($file_ext)."','".sanitize($_POST['createdon'])."', '".sanitize($target_file)."')");
		$db->close();
		echo "<script>window.location.href='adverts.php?status=1'</script>";
	}else if ($sub_type == 'sub_del') {
		$arr = $db->query("SELECT * FROM {$table_name} WHERE id=".sanitize($_GET['delete']));
		$del = $arr->fetchArray();
		if (!empty($del['path']) && file_exists($del['path']) && strpos($del['path'], 'ads/') === 0) {
			unlink($del['path']);
		}
		$db->exec("DELETE FROM {$table_name} WHERE id=".sanitize($_GET['delete']));
	}
	$db->close();
}



?>
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content" style="background-color: black;">
			<div class="modal-header">
				<h2 style="color: white;">Confirm</h2>
			</div>
			<div class="modal-body" style="color: white;">
				Do you really want to delete?
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
				<a style="color: white;" class="btn btn-danger btn-ok">Delete</a>
			</div>
		</div>
	</div>
</div>
<?php
if (isset($_GET['create'])){

//create form
?>


        <div class="col-md-6 mx-auto">
            <div class="card-body">
                <div class="card bg-primary text-white">
                    <div class="card-header card-header-warning">
                        <center>
                            <h2><i class="icon icon-bullhorn"></i> ADVERTS</h2>
                        </center>
                    </div>
                    
                    <div class="card-body">
                        <div class="col-12">
                            <h3>Upload Advert</h3>
                        </div>
                            <form action="" method="post" enctype="multipart/form-data" id="advert-upload-form">
                                <div class="form-group">
                                    <div class="form-group form-float form-group-lg">
                                        <div class="form-line">
                                            <label class="form-label"><strong>Title</strong></label>
                                            <input type="text" class="form-control" name="title" placeholder="Title">
                                            <input type="hidden" name="createdon" value="<?=date("Y-m-d h:i:s")?>">
                                        </div>
                                    </div>

                                    <div class="form-group form-float form-group-lg">
                                        <label class="form-label"><strong>Advert Image or Video</strong></label>
                                        <div id="drop-zone" style="border:2px dashed rgba(255,255,255,.65); border-radius:16px; padding:30px 20px; text-align:center; background:rgba(0,0,0,.18); cursor:pointer; transition:all .2s ease;">
                                            <input type="file" id="ad_image" name="ad_image" accept="image/*,video/mp4,video/webm" required style="display:none;">
                                            <div style="font-size:46px; line-height:1; margin-bottom:10px;">📸</div>
                                            <div style="font-size:20px; font-weight:700;">Drop image or video here or click to browse</div>
                                            <div style="margin-top:8px; opacity:.9;">JPG, JPEG, PNG, GIF, WEBP, MP4, WEBM · Max 50MB</div>
                                        </div>
                                    </div>

                                    <div id="preview-wrap" style="display:none; margin-top:18px; text-align:center;">
                                        <div style="margin-bottom:10px; font-weight:700;">Preview</div>
                                        <img id="image-preview" src="" alt="Preview" style="display:none; max-width:100%; max-height:320px; border-radius:16px; box-shadow:0 8px 24px rgba(0,0,0,.35); border:3px solid rgba(255,255,255,.25);">
                                        <video id="video-preview" style="display:none; max-width:100%; max-height:320px; border-radius:16px; box-shadow:0 8px 24px rgba(0,0,0,.35); border:3px solid rgba(255,255,255,.25); background:#000;" controls muted playsinline preload="metadata"></video>
                                        <div id="file-name" style="margin-top:10px; word-break:break-word;"></div>
                                    </div>
                                </div>
                               <br>

                                <div class="form-group">
                                    <center>
                                        <button class="btn btn-info " name="submit" type="submit">
                                            <i class="icon icon-check"></i> Upload Advert
                                        </button>
                                    </center>
                                </div>
                            </form>
                    </div>
                </div>
            </div>
        </div>
<?php
 }else{
//main table/form
	 ?>
        <div class="col-md-12 mx-auto">
            <div class="card-body">
                <div class="card bg-primary text-white">
                    
                    <div class="card-body">
						</div>
				    </div>
                </div>
            </div>
            <div id="ftu" class="card-body">
                <div class="card bg-primary text-white">
                    <div class="card-header card-header-warning">
                        <center>
                            <h2><i class="icon icon-commenting"></i> ADVERT's</h2>
                        </center>
                    </div>
                    <div class="card-body" >
                        <div class="col-12">
                        	<center>
	        					<a id="button" href="./<?php echo $base_file ?>?create" class="btn btn-info">New ADVERT</a>
	        				</center>
    					</div>
						<br>
						<div class="table-responsive">
							<table class="table table-striped table-sm">
							<thead style="color:white!important">
								<tr>
								<th>Index</th>
								<th>Title</th>
								<th>Created</th>
								<th>File Path</th>
								<th>Delete</th>
								</tr>
							</thead>
							<?php while ($row = $res->fetchArray()) {?>
							<tbody>
								<tr>
								<td><?=$row['id'] ?></td>
								<td><?=$row['title'] ?></a></td>
								<td><?=$row['createdon'] ?></a></td>
								<td>
				<?php $ext = strtolower(pathinfo($row['path'], PATHINFO_EXTENSION)); ?>
				<?php if (in_array($ext, ['mp4','webm'])) { ?>
					<video src="<?=$row['path'] ?>" height="80" width="120" muted playsinline preload="metadata" style="background:#000; border:3px solid rgba(255,255,255,.25); border-radius:8px;"></video>
				<?php } else { ?>
					<img src="<?=$row['path'] ?>" alt="" border=3 height=80 width=120></img>
				<?php } ?>
				</td>
								<td>
								<a class="btn btn-danger btn-ok" href="#" data-href="./<?=$base_file ?>?delete=<?=$row['id'] ?>" data-toggle="modal" data-target="#confirm-delete"><i class="fa fa-trash-o"></i></a>
								</td>
								</tr>
							</tbody>
							<?php }?>
							</table>
						</div>
						</div>
					</div>
				</div>
			</div>
		</div>
<?php }?>

<?php include ('includes/footer.php');?>
<?=$resT=='rt'?"<script>document.getElementById('ftu').style.display = 'none'</script>":'' ?>
<script>


function setupAdvertUploader(){
    var dropZone = document.getElementById('drop-zone');
    var fileInput = document.getElementById('ad_image');
    var previewWrap = document.getElementById('preview-wrap');
    var preview = document.getElementById('image-preview');
    var videoPreview = document.getElementById('video-preview');
    var fileName = document.getElementById('file-name');

    if (!dropZone || !fileInput) {
        return;
    }

    function resetPreview(){
        previewWrap.style.display = 'none';
        preview.style.display = 'none';
        preview.removeAttribute('src');
        if (videoPreview) {
            videoPreview.pause();
            videoPreview.style.display = 'none';
            videoPreview.removeAttribute('src');
            videoPreview.load();
        }
        fileName.textContent = '';
    }

    function showPreview(file){
        if (!file) {
            resetPreview();
            return;
        }

        previewWrap.style.display = 'block';
        fileName.textContent = file.name;

        if (file.type.match(/^image\//)) {
            if (videoPreview) {
                videoPreview.pause();
                videoPreview.style.display = 'none';
                videoPreview.removeAttribute('src');
                videoPreview.load();
            }
            var reader = new FileReader();
            reader.onload = function(e){
                preview.src = e.target.result;
                preview.style.display = 'inline-block';
            };
            reader.readAsDataURL(file);
            return;
        }

        if (file.type.match(/^video\//) && videoPreview) {
            preview.style.display = 'none';
            preview.removeAttribute('src');
            videoPreview.src = URL.createObjectURL(file);
            videoPreview.style.display = 'inline-block';
            videoPreview.load();
            return;
        }

        resetPreview();
    }

    dropZone.addEventListener('click', function(){
        fileInput.click();
    });

    fileInput.addEventListener('change', function(){
        if (fileInput.files && fileInput.files[0]) {
            showPreview(fileInput.files[0]);
        }
    });

    ['dragenter', 'dragover'].forEach(function(eventName){
        dropZone.addEventListener(eventName, function(e){
            e.preventDefault();
            e.stopPropagation();
            dropZone.style.background = 'rgba(255,255,255,.12)';
            dropZone.style.borderColor = '#ffffff';
            dropZone.style.transform = 'scale(1.01)';
        });
    });

    ['dragleave', 'dragend', 'drop'].forEach(function(eventName){
        dropZone.addEventListener(eventName, function(e){
            e.preventDefault();
            e.stopPropagation();
            dropZone.style.background = 'rgba(0,0,0,.18)';
            dropZone.style.borderColor = 'rgba(255,255,255,.65)';
            dropZone.style.transform = 'scale(1)';
        });
    });

    dropZone.addEventListener('drop', function(e){
        var files = e.dataTransfer.files;
        if (files && files.length) {
            fileInput.files = files;
            showPreview(files[0]);
        }
    });
}

document.addEventListener('DOMContentLoaded', setupAdvertUploader);

function yesnoCheck(that){

    if (that.value == "ua"){
        document.getElementById("ftu").style.display = "block";
    }else{
        document.getElementById("ftu").style.display = "none";
    }
}
</script>
</body>
</html>