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

include ("conn.php");

// Handle banner upload
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['banner'])) {
    include 'db_connection.php'; // Make sure to include your DB connection
 if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}


    $upload_dir = "uploads/Banners/";
    $domain = "https://spingoo.site/AdminMR/";

    // Generate unique file name
    $timestamp = time();  // Get current timestamp
    $random_str = substr(md5(rand()), 0, 7);  // Generate a random string (7 characters)

    // Combine the parts into the desired format
    $file_name = $timestamp . "_Banner_" . date("YmdHis") . $random_str . "." . pathinfo($_FILES["banner"]["name"], PATHINFO_EXTENSION);
    $target_path = $upload_dir . $file_name;
    $full_url = $domain . $target_path;

    // Upload file to server
    if (move_uploaded_file($_FILES["banner"]["tmp_name"], $target_path)) {
        // Insert banner URL into database
        $stmt = mysqli_prepare($conn, "INSERT INTO banners (banner_url, is_active) VALUES (?, 1)");
        mysqli_stmt_bind_param($stmt, "s", $full_url);

        if (mysqli_stmt_execute($stmt)) {
            echo "<script>alert('Banner uploaded and saved successfully!'); window.location.href=window.location.href;</script>";
        } else {
            echo "<script>alert('File uploaded, but failed to save to database.');</script>";
        }

        mysqli_stmt_close($stmt);
    } else {
        echo "<script>alert('Failed to upload the banner.');</script>";
    }
}


// Update redirect URL logic
if (isset($_POST['updateLink'])) {
    $id = mysqli_real_escape_string($conn, $_POST['id']);
    $redirectUrl = mysqli_real_escape_string($conn, $_POST['redirectUrl']);

    $update_url = "UPDATE banners SET redirect_url = '$redirectUrl' WHERE id = '$id'";
    if (mysqli_query($conn, $update_url)) {
        echo "<script>alert('Redirect URL updated successfully!');</script>";
    } else {
        echo "<script>alert('Failed to update URL.');</script>";
    }
}

// Delete banner logic
if (isset($_POST['deleteBanner'])) {
    include 'db_connection.php'; // ensure DB connection is included

    $banner_id = intval($_POST['id']); // Sanitize input

    // Step 1: Fetch banner URL from DB
    $fetch_query = "SELECT banner_url FROM banners WHERE id = $banner_id";
    $result = mysqli_query($conn, $fetch_query);
    $row = mysqli_fetch_assoc($result);

    if ($row) {
        $banner_url = $row['banner_url'];

        // Step 2: Extract relative path from URL
        $parsed_url = parse_url($banner_url, PHP_URL_PATH); // /newadmin/uploads/xyz.jpg

        // Step 3: Convert to full path relative to this script
        $file_path = $_SERVER['DOCUMENT_ROOT'] . $parsed_url;

        // Optional: If your admin panel is in a subdir and path doesn't match, use this instead:
        // $file_path = __DIR__ . str_replace('/newadmin', '', $parsed_url);

        // Step 4: Delete file from server if it exists
        if (file_exists($file_path)) {
            unlink($file_path);
        }

        // Step 5: Delete DB entry
        $delete_query = "DELETE FROM banners WHERE id = $banner_id";
        if (mysqli_query($conn, $delete_query)) {
            echo "<script>alert('Banner deleted successfully.'); window.location.href = window.location.href;</script>";
        } else {
            echo "<script>alert('Failed to delete the banner from database.');</script>";
        }
    } else {
        echo "<script>alert('Banner not found.');</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/mdi/css/materialdesignicons.min.css">
  <link rel="stylesheet" href="vendors/feather/feather.css">
  <link rel="stylesheet" href="vendors/base/vendor.bundle.base.css">
  <link rel="stylesheet" href="vendors/flag-icon-css/css/flag-icon.min.css"/>
  <link rel="stylesheet" href="vendors/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="vendors/jquery-bar-rating/fontawesome-stars-o.css">
  <link rel="stylesheet" href="vendors/jquery-bar-rating/fontawesome-stars.css">
  <link rel="stylesheet" href="css/style.css">
  <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css">
  <link rel="stylesheet" href="https://cdn.datatables.net/fixedheader/3.2.3/css/fixedHeader.dataTables.min.css">
  <link rel="shortcut icon" href="images/favicon.png" />
  <style>
  
  /* Base Styling */
body.bg-light {
    background-color: #0d1117 !important;
    color: #e6edf3;
    font-family: 'Segoe UI', sans-serif;
}

/* Container Styling */
.container, .container-fluid {
    background-color: transparent !important;
}

/* Headings */
h2.text-primary, h3.text-success, h3.text-info {
    color: #58a6ff !important;
}

/* Form Cards */
form.bg-white,
.table-responsive.bg-white {
    background-color: #161b22 !important;
    border: 1px solid #30363d;
    color: #c9d1d9;
}

/* Inputs & Selects */
input.form-control,
select.form-select,
input[type="text"],
input[type="file"] {
    background-color: #0d1117;
    color: #e6edf3;
    border: 1px solid #30363d;
}

input::placeholder {
    color: #8b949e;
}

/* Buttons */
.btn-primary {
    background-color: #238636;
    border-color: #2ea043;
}

.btn-success {
    background-color: #0969da;
    border-color: #218bff;
}

.btn-danger {
    background-color: #da3633;
    border-color: #f85149;
}

.btn:hover {
    opacity: 0.9;
}

/* Table */
table.table {
    background-color: transparent;
    color: #e6edf3;
}

.table-striped tbody tr:nth-of-type(odd) {
    background-color: #161b22;
}

.table-striped tbody tr:nth-of-type(even) {
    background-color: #0d1117;
}

table.table th {
    color: #58a6ff;
    border-bottom: 1px solid #30363d;
}

table.table td, table.table th {
    border-color: #30363d;
}

/* Navbar */
.navbar {
    background-color: #161b22 !important;
    border-bottom: 1px solid #30363d;
}

.navbar .navbar-brand img {
    max-height: 40px;
}

.navbar .nav-link, .navbar .icon-cog {
    color: #e6edf3 !important;
}

/* Sidebar */
.sidebar {
    background-color: #0d1117;
    border-right: 1px solid #30363d;
}

.sidebar .user-name,
.sidebar .user-designation {
    color: #58a6ff;
}

/* Dropdown */
.dropdown-menu {
    background-color: #161b22;
    border: 1px solid #30363d;
}

.dropdown-item {
    color: #e6edf3;
}

.dropdown-item:hover {
    background-color: #21262d;
}

	.cool-input {
        border: 2px solid #007bff;
        border-radius: 0.25rem;
        padding: 0.5rem 1rem;
        font-size: 1rem;
        transition: all 0.3s ease;
    }
    .cool-input:focus {
        border-color: #0056b3;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }
    .cool-input::placeholder {
        color: #6c757d;
        opacity: 1;
    }
	.cool-button {
        padding: 0.5rem 1rem;
        font-size: 1rem;
        border-radius: 0.25rem;
        transition: all 0.3s ease;
    }
    .cool-button:hover {
        background-color: #0056b3;
        color: #fff;
    }
    .cool-button.btn-secondary:hover {
        background-color: #343a40;
        color: #fff;
    }
	#copied{
		visibility: hidden;
		z-index: 1;
		position: fixed;
		bottom: 50%;
		background-color: #333;
		color: #fff;
		border-radius: 6px;
		padding: 16px;
		max-width: 250px;
		font-size: 17px;
	}	   
	#copied.show {
		visibility: visible;
		-webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
		animation: fadein 0.5s, fadeout 0.5s 2.5s;
	}
  </style>
</head>
<body>
  <div class="container-scroller">
    <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
      <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
        <a class="navbar-brand brand-logo" href="dashboard.php"><img src="images/logo.png" alt="logo"/></a>
        <a class="navbar-brand brand-logo-mini" href="dashboard.php"><img src="images/logo-mini.png" alt="logo"/></a>
      </div>
      <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end">
        <button class="navbar-toggler navbar-toggler align-self-center" type="button" data-toggle="minimize">
          <span class="icon-menu"></span>
        </button>       
        <ul class="navbar-nav navbar-nav-right">           
          <li class="nav-item dropdown d-flex mr-4 ">
            <a class="nav-link count-indicator dropdown-toggle d-flex align-items-center justify-content-center" id="notificationDropdown" href="#" data-toggle="dropdown">
              <i class="icon-cog"></i>
            </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list" aria-labelledby="notificationDropdown">
              <p class="mb-0 font-weight-normal float-left dropdown-header">Settings</p>              
              <a class="dropdown-item preview-item" href="logout.php">
                  <i class="icon-inbox"></i> Logout
              </a>
            </div>
          </li>
        </ul>
        <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="offcanvas">
          <span class="icon-menu"></span>
        </button>
      </div>
    </nav>
    <div class="container-fluid page-body-wrapper">
      <nav class="sidebar sidebar-offcanvas" id="sidebar">
        <div class="user-profile">
          <div class="user-image">
            <div class="user-image">
            <img src="images/faces/fx.png">
          </div>
          <div class="user-name">
              FX DEVLOPER
          </div>
          <div class="user-designation">
              Admin
          </div>
        </div>
        <?php include 'compass.php';?>
      </nav>
        				
    <body class="bg-light">
    <div class="container mt-5">
    <!-- ✅ Upload New Banner -->
        <h2 class="mb-4 text-primary">Upload New Banner</h2>
        <form method="POST" enctype="multipart/form-data" class="p-4 bg-white shadow rounded">
            <div class="mb-3">
                <input type="file" name="banner" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary">Upload</button>
        </form>

        <!-- ✅ Update Only URL -->
        <h3 class="mt-5 text-success">Update Banner URL</h3>
        <form method="POST" class="p-4 bg-white shadow rounded">
            <div class="mb-3">
                <select name="id" class="form-select" required>
                    <option value="">Select Banner</option>
                    <?php
                    $sel_banners = "SELECT id, banner_url FROM banners WHERE is_active='0' OR is_active='1' ORDER BY id DESC";
                    $banner_r = mysqli_query($conn, $sel_banners);
                    while ($row = mysqli_fetch_assoc($banner_r)) {
                        echo '<option value="' . $row['id'] . '">' . $row['banner_url'] . '</option>';
                    }
                    ?>    
                </div>
            <div class="mb-3">
                <input type="text" name="redirectUrl" class="form-control" placeholder="Enter Redirect URL" required>
            </div>
            <button type="submit" name="updateLink" class="btn btn-success">Update</button>
        </form>

        <!-- ✅ Display All Banners with Delete Option -->
        <h3 class="mt-5 text-info">All Banners</h3>
        <div class="table-responsive bg-white shadow rounded p-3">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>Banner</th>
                        <th>Redirect URL</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                        $sel_banners = "SELECT * FROM banners WHERE is_active='0' OR is_active='1' ORDER BY id DESC";
                        $banner_r = mysqli_query($conn, $sel_banners);
                        while ($row = mysqli_fetch_array($banner_r)) {
                        ?>    
                    <tr>
                            <td><img src="<?php echo $row['banner_url']; ?>" alt="Banner" width="120"></td>
                            <td><a href="<?php echo $row['redirect_url']; ?>" target="_blank">
                                <?php echo $row['redirect_url']; ?>
                            </a></td>
                            <td>
                                <form method="POST" style="display:inline;">
                                    <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                    <button type="submit" name="deleteBanner" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure?')">Delete</button>
                                </form>
                            </td>
                    </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
    </body>    
</html>
