<?php
session_start();
if ($_SESSION['unohs'] == null) {
	header("location:index.php?msg=unauthorized");
}
include("conn.php");

// 📤 Image Upload Logic
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) {
			$uploadOk = 1;
		} else {
			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("Only JPG, JPEG, PNG files are allowed.");</script>';
		$uploadOk = 0;
	}

	if ($uploadOk) {
		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("Image uploaded and added to database.");</script>';
			} else {
				echo '<script>alert("Database insert error.");</script>';
			}
		} else {
			echo '<script>alert("Error uploading file.");</script>';
		}
	}
}

// ✅ Set active image
if (isset($_POST['upiid'])) {
	$a_id = mysqli_real_escape_string($conn, $_POST['upiid']);

	// Reset current active
	mysqli_query($conn, "UPDATE images SET status='0' WHERE status='1'");

	// Set new active
	mysqli_query($conn, "UPDATE images SET status='1' WHERE filename='$a_id'");
}

// ❌ Delete image
if (isset($_POST['delete_image'])) {
	$filenameToDelete = mysqli_real_escape_string($conn, $_POST['delete_image']);
	$filepath = "../images/" . $filenameToDelete;

	// Delete from DB first
	$deleteQuery = "DELETE FROM images WHERE filename='$filenameToDelete'";
	if (mysqli_query($conn, $deleteQuery)) {
		// Delete actual file if exists
		if (file_exists($filepath)) {
			unlink($filepath);
		}
		echo '<script>alert("Image deleted successfully.");</script>';
	} else {
		echo '<script>alert("Failed to delete image from database.");</script>';
	}
}
?>


        <?php include 'header.php';?>
      </nav>
     <div class="main-panel">
  <div class="content-wrapper">
    <div class="row">
      <div class="col-sm-12 mb-4 mb-xl-0">
        <h4 class="font-weight-bold text-dark">Add UPI Image</h4>
      </div>
    </div>

    <!-- Upload Image Form -->
    <div class="row mb-4">
      <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data" class="w-100" style="margin:5px; padding:8px;">
        <h5>Select image to upload:</h5>
        <div class="d-flex align-items-center">
          <input type="file" name="image" id="image" class="form-control" style="height: 40px;" required>
        </div>
        <div class="d-flex align-items-center mt-3">
          <input type="submit" value="Upload Image" name="submit" class="btn btn-primary mr-2">
        </div>
      </form>
    </div>

    <!-- Display Uploaded Images + Action Options -->
    <div class="row">
      <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" id="upisave" method="post" autocomplete="off" class="w-100">
        <div class="table-responsive">
          <table class="table table-bordered text-center">
            <thead class="thead-light">
              <tr>
                <th>Select</th>
                <th>Preview</th>
                <th>Filename</th>
                <th>Status</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <?php
                $sel_upi = "SELECT * FROM images ORDER BY id DESC";
                $upi_r = mysqli_query($conn, $sel_upi);
                while ($row = mysqli_fetch_array($upi_r)) {
              ?>
              <tr>
                <td>
                  <input type="radio" name="upiid" value="<?php echo $row['filename']; ?>" <?php if ($row['status'] == 1) echo "checked"; ?> />
                </td>
                <td>
                  <img src="../images/<?php echo $row['filename']; ?>" height="60">
                </td>
                <td><?php echo $row['filename']; ?></td>
                <td>
                  <?php echo ($row['status'] == 1) ? '<span class="badge badge-success">Active</span>' : '<span class="badge badge-secondary">Inactive</span>'; ?>
                </td>
                <td>
                  <button type="submit" name="delete_image" value="<?php echo $row['filename']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this image?')">Delete</button>
                </td>
              </tr>
              <?php } ?>
            </tbody>
          </table>
        </div>
        <button type="submit" class="btn btn-success mt-2">Save Active Image</button>
      </form>
    </div>
  </div>
</div>
      </div>
    </div>
  </div>
  
  <script>	
	if ( window.history.replaceState ) {
        window.history.replaceState( null, null, window.location.href );
    }
  </script>
</body>

</html>