<?php
	session_start();
	if($_SESSION['unohs'] == null){
		header("location:index.php?msg=unauthorized");
	}
?>
<?php
	include ("conn.php");
	
	/* ========== IMAGE UPLOAD (ORIGINAL) ========== */
	if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["image"])) {
		$target_dir = "../images/";
		$target_file = $target_dir . basename($_FILES["image"]["name"]);
		$uploadOk = 1;
		$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

		if(isset($_POST["submit"])) {
			$check = getimagesize($_FILES["image"]["tmp_name"]);
			if($check === false) {
				echo '<script>alert("File is not an image.");</script>';
				$uploadOk = 0;
			}
		}

		if (file_exists($target_file)) {
			echo '<script>alert("Sorry, file already exists.");</script>';
			$uploadOk = 0;
		}

		if ($_FILES["image"]["size"] > 500000) {
			echo '<script>alert("Sorry, your file is too large.");</script>';
			$uploadOk = 0;
		}

		if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
			echo '<script>alert("Sorry, only JPG, JPEG, PNG files are allowed.");</script>';
			$uploadOk = 0;
		}

		if ($uploadOk == 1) {
			if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
				$filename = basename($_FILES["image"]["name"]);
				$sql = "INSERT INTO images (filename) VALUES ('$filename')";
				if ($conn->query($sql) === TRUE) {
					echo '<script>alert("Record added to database successfully");</script>';
				} else {
					echo '<script>alert("Error adding record");</script>';
				}
			} else {
				echo '<script>alert("Sorry, there was an error uploading your file.");</script>';
			}
		}
	}

	/* ========== SET ACTIVE IMAGE (ORIGINAL) ========== */
	if(isset($_POST['upiid'])){
		$a_id = $_POST['upiid'];
		$sql_s = "SELECT * FROM images WHERE filename = '".$a_id."'";
		$run = mysqli_query($conn, $sql_s);

		$sql_d = "SELECT * FROM images WHERE status = '1'";		
		$run_d = mysqli_query($conn, $sql_d);
		$rund_f = mysqli_fetch_array($run_d);

		$ch_s0 = "UPDATE images SET status='0' WHERE id='".$rund_f['id']."'";
		mysqli_query($conn, $ch_s0);

		$run_f = mysqli_fetch_array($run);
		$ch_s1 = "UPDATE images SET status='1' WHERE id='".$run_f['id']."'";
		mysqli_query($conn, $ch_s1);
	}

	/* ========== DELETE IMAGE (ONLY NEW) ========== */
	if(isset($_POST['delete_image'])){
		$del_img = mysqli_real_escape_string($conn, $_POST['delete_image']);

		// delete from DB
		$del_sql = "DELETE FROM images WHERE filename='".$del_img."'";
		if(mysqli_query($conn, $del_sql)){
			// delete file from folder
			$file_path = "../images/".$del_img;
			if(file_exists($file_path)){
				unlink($file_path);
			}
			echo '<script>alert("Image Deleted");</script>';
		}else{
			echo '<script>alert("Failed to Delete Image");</script>';
		}
	}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Dashboard</title>

  <link rel="stylesheet" href="vendors/base/vendor.bundle.base.css">
  <link rel="stylesheet" href="css/style.css">

  <style>
	/* ===== Responsive Image Row (NEW) ===== */
	.img-row{
		display:flex;
		align-items:center;
		justify-content:space-between;
		padding:8px 10px;
		border-bottom:1px solid #eee;
		flex-wrap:wrap;
	}
	.img-left{
		display:flex;
		align-items:center;
		gap:8px;
		flex:1;
		word-break:break-all;
	}
	.img-right{
		margin-top:5px;
	}
	@media (max-width: 600px){
		.img-row{
			flex-direction:column;
			align-items:flex-start;
		}
		.img-right{
			width:100%;
			text-align:right;
			margin-top:8px;
		}
	}
  </style>
</head>

<body>
<div class="container-scroller">

<div class="main-panel">
<div class="content-wrapper">

<h4 class="font-weight-bold text-dark">Add UPI Image</h4>

<!-- UPLOAD FORM -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data" style="margin:5px; padding:8px;">
	<h4>Select image to upload:</h4>
	<div class="d-flex align-items-center">	
		<input type="file" name="image" id="image" class="flex-grow-1 cool-input" style="height: 40px;">
	</div>
	<div class="d-flex align-items-center mt-3">
		<input type="submit" value="Upload Image" name="submit" class="btn btn-primary cool-button mr-2">
	</div>
</form>

<hr>

<?php
$sel_upi = "SELECT * FROM images WHERE status='0' OR status='1'";
$upi_r = mysqli_query($conn, $sel_upi);
?>

<!-- IMAGE LIST + DELETE -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">

<?php while ($row = mysqli_fetch_array($upi_r)) { ?>

<div class="img-row">
	<div class="img-left">
		<input name="upiid" type="radio"
			value="<?php echo $row['filename']; ?>"
			<?php if($row['status']==1){echo "checked";} ?> />

		<label><?php echo $row['filename']; ?></label>
	</div>

	<div class="img-right">
		<button type="submit"
			name="delete_image"
			value="<?php echo $row['filename']; ?>"
			class="btn btn-danger btn-sm"
			onclick="return confirm('Delete this image?');">
			Delete
		</button>
	</div>
</div>

<?php } ?>

<button type="submit" class="btn btn-primary cool-button mr-2" style="margin-top: 10px;">
	Save
</button>

</form>

</div>
</div>
</div>

<!-- IMPORTANT: Back button issue FIX — history.replaceState REMOVED -->

<script src="vendors/base/vendor.bundle.base.js"></script>
<script src="js/off-canvas.js"></script>
<script src="js/template.js"></script>

</body>
</html>
