<?php
// --- 1. SUPER DEBUGGING (Error Dikhaane Ke Liye) ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

$msg = "";
$msg_type = "";

// --- 2. UPLOAD LOGIC (With Absolute Path) ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Check if $_FILES is empty (Server Limit Issue)
    if (empty($_FILES) && empty($_POST)) {
        $msg = "⚠️ Server Limit Error: The file is too big for your server settings (post_max_size). Try a smaller image.";
        $msg_type = "error";
    }
    elseif (isset($_FILES["image"])) {
        
        // Use Absolute Path (Sabse Safe Tarika)
        $target_dir = dirname(__DIR__) . "/images/";
        
        // Folder Check & Create
        if (!is_dir($target_dir)) {
            if (!mkdir($target_dir, 0777, true)) {
                $msg = "❌ Error: Could not create folder at: " . $target_dir;
                $msg_type = "error";
            }
        }

        // Write Permission Check
        if (empty($msg) && !is_writable($target_dir)) {
            $msg = "❌ Error: Server cannot write to folder: " . $target_dir . " (Check Permissions 777)";
            $msg_type = "error";
        }

        if (empty($msg)) {
            $filename = basename($_FILES["image"]["name"]);
            $target_file = $target_dir . $filename;
            $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
            $uploadOk = 1;

            // Basic Validation
            if ($_FILES["image"]["size"] > 5000000) { // 5MB
                $msg = "⚠️ File is too large (Max 5MB).";
                $uploadOk = 0;
                $msg_type = "error";
            }
            elseif ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
                $msg = "⚠️ Only JPG, JPEG & PNG files are allowed.";
                $uploadOk = 0;
                $msg_type = "error";
            }

            // Attempt Upload
            if ($uploadOk == 1) {
                if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
                    // DB Insert
                    $sql = "INSERT INTO images (filename, status) VALUES ('$filename', '0')";
                    if ($conn->query($sql) === TRUE) {
                        $msg = "✅ Image Uploaded Successfully!";
                        $msg_type = "success";
                    } else {
                        $msg = "❌ DB Error: " . $conn->error;
                        $msg_type = "error";
                    }
                } else {
                    // Specific Upload Error
                    $msg = "❌ Failed to move uploaded file. Check server logs.";
                    $msg_type = "error";
                }
            }
        }
    }
}

// --- 3. ACTIVATE IMAGE ---
if (isset($_POST['upiid'])) {
    $a_id = mysqli_real_escape_string($conn, $_POST['upiid']);
    mysqli_query($conn, "UPDATE images SET status='0'");
    if(mysqli_query($conn, "UPDATE images SET status='1' WHERE filename='$a_id'")){
        $msg = "✨ Active QR Code Updated!";
        $msg_type = "success";
    }
}

// --- 4. DELETE IMAGE ---
if (isset($_GET['delete'])) {
    $del_file = mysqli_real_escape_string($conn, $_GET['delete']);
    $del_sql = "DELETE FROM images WHERE filename = '$del_file'";
    if (mysqli_query($conn, $del_sql)) {
        $file_path = dirname(__DIR__) . "/images/" . $del_file;
        if (file_exists($file_path)) { unlink($file_path); }
        echo "<script>alert('🗑️ Deleted!'); window.location.href='addupiimg.php';</script>";
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=1200, initial-scale=0.1">
    <title>Manage QR Codes</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <link rel="stylesheet" href="css/style.css">
    <link rel="shortcut icon" href="images/favicon.png" />

    <style>
        /* =========================================
           ULTRA PRO LIGHT THEME
           ========================================= */
        :root {
            --primary-grad: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-grad: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            --bg-body: #f7f9fc;
            --bg-white: #ffffff;
            --text-main: #2d3436;
            --border-color: #eef2f7;
        }

        body {
            background-color: var(--bg-body) !important;
            color: var(--text-main);
            font-family: 'Poppins', sans-serif;
            font-weight: 600;
        }

        /* --- SIDEBAR & NAVBAR --- */
        .sidebar { background: #ffffff !important; border-right: 1px solid var(--border-color); }
        .sidebar .nav-link { color: #555 !important; font-weight: 600; }
        .sidebar .nav-link:hover { background: #f0f3ff !important; color: #764ba2 !important; }
        .user-profile { background: #fff !important; border-bottom: 1px solid var(--border-color); }
        .user-name { color: #000 !important; font-weight: 800 !important; }
        
        .navbar { background: #ffffff !important; box-shadow: 0 4px 20px rgba(0,0,0,0.03) !important; }
        .navbar .navbar-brand-wrapper { background: #ffffff !important; }
        .navbar-toggler { border: none !important; outline: none !important; }
        .fa-bars { font-size: 1.5rem; color: #333 !important; }

        /* --- ALERT BOX (DEBUGGING) --- */
        .alert-box {
            padding: 15px; border-radius: 12px; margin-bottom: 25px;
            font-weight: 700; text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        .alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .alert-error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }

        /* --- UPLOAD CARD --- */
        .upload-card {
            background: var(--bg-white);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.08);
            border: 2px dashed #cbd5e0;
            text-align: center;
            margin-bottom: 30px;
            transition: 0.3s;
        }
        .upload-card:hover { border-color: #764ba2; background: #fdfaff; }

        .custom-file-upload {
            display: inline-block;
            padding: 12px 30px;
            cursor: pointer;
            background: var(--primary-grad);
            color: #fff;
            border-radius: 50px;
            font-weight: 800;
            transition: 0.3s;
            box-shadow: 0 8px 20px rgba(118, 75, 162, 0.3);
        }
        .custom-file-upload:hover { transform: translateY(-2px); box-shadow: 0 12px 25px rgba(118, 75, 162, 0.4); }
        
        #image { display: none; }

        /* --- IMAGE GALLERY --- */
        .gallery-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
        }

        .img-card {
            background: #fff;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            border: 2px solid #eef2f7;
            position: relative;
            transition: 0.3s;
        }
        .img-card:hover { transform: translateY(-5px); box-shadow: 0 15px 30px rgba(0,0,0,0.1); }
        .img-card.active { border-color: #38ef7d; box-shadow: 0 0 15px rgba(56, 239, 125, 0.2); }

        .qr-preview {
            width: 100%;
            height: 180px;
            object-fit: contain;
            padding: 15px;
            background: #f9f9f9;
        }

        .card-actions {
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #fff;
            border-top: 1px solid #eee;
        }

        .custom-radio { accent-color: #38ef7d; transform: scale(1.5); cursor: pointer; }
        
        .status-badge {
            position: absolute; top: 10px; right: 10px;
            background: var(--success-grad); color: #fff;
            padding: 5px 10px; border-radius: 20px;
            font-size: 0.7rem; font-weight: 900;
            box-shadow: 0 3px 10px rgba(0,0,0,0.2);
        }

        .btn-delete {
            color: #ff4b2b;
            background: #fff0f0;
            width: 35px; height: 35px;
            border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            transition: 0.2s;
            text-decoration: none;
        }
        .btn-delete:hover { background: #ff4b2b; color: #fff; }

        .btn-save-float {
            position: fixed; bottom: 30px; right: 30px;
            background: var(--success-grad); color: #fff;
            padding: 15px 30px; border-radius: 50px;
            font-size: 1.1rem; font-weight: 800; border: none;
            box-shadow: 0 10px 30px rgba(56, 239, 125, 0.4);
            cursor: pointer; z-index: 999;
            transition: 0.3s;
            display: flex; align-items: center; gap: 10px;
        }
        .btn-save-float:hover { transform: scale(1.05); }

        @media (max-width: 768px) {
            .content-wrapper { padding: 15px !important; }
            .gallery-grid { grid-template-columns: repeat(2, 1fr); gap: 15px; }
            .qr-preview { height: 140px; }
        }
    </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">
                    <h4 style="color:#764ba2; font-weight:900; margin:0; letter-spacing:-1px;">QR<span style="color:#38ef7d;">CODE</span></h4>
                </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">
                    <i class="fa-solid fa-bars" style="font-size: 1.5rem; color: #333;"></i>
                </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" style="color:#333; font-size:1.2rem;"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list" aria-labelledby="notificationDropdown">
                            <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">
                    <i class="fa-solid fa-bars" style="font-size: 1.5rem; color: #333;"></i>
                </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">
                        <img src="images/faces/face28.png">
                    </div>
                    <div class="user-name">AB Coders</div>
                    <div class="user-designation">Admin</div>
                </div>
                <?php include 'compass.php'; ?>
            </nav>

            <div class="main-panel">
                <div class="content-wrapper">
                    
                    <?php if(!empty($msg)): ?>
                        <div class="alert-box <?php echo ($msg_type == 'success') ? 'alert-success' : 'alert-error'; ?>">
                            <?php echo $msg; ?>
                        </div>
                    <?php endif; ?>

                    <div class="row justify-content-center">
                        <div class="col-md-10">
                            <form action="" method="post" enctype="multipart/form-data">
                                <div class="upload-card">
                                    <i class="fa-solid fa-cloud-arrow-up" style="font-size:3rem; color:#764ba2; margin-bottom:15px;"></i>
                                    <div style="font-size:1.2rem; font-weight:800; color:#333; margin-bottom:5px;">Upload QR Code</div>
                                    <div style="font-size:0.9rem; color:#888; margin-bottom:20px;">Supported: JPG, PNG (Max 5MB)</div>
                                    
                                    <label for="image" class="custom-file-upload">
                                        <i class="fa-solid fa-image"></i> Select Image
                                    </label>
                                    <input type="file" name="image" id="image" onchange="this.form.submit()">
                                </div>
                            </form>
                        </div>
                    </div>

                    <form action="" id="upisave" method="post">
                        <div class="gallery-grid">
                            <?php
                                $sel_upi = "SELECT * FROM images";
                                $upi_r = mysqli_query($conn, $sel_upi);
                                
                                if(mysqli_num_rows($upi_r) > 0) {
                                    while ($row = mysqli_fetch_array($upi_r)) {
                                        $isActive = ($row['status'] == 1);
                                        // Using relative path for display, assuming images are in ../images/ from this script location
                                        $imgSrc = "../images/" . $row['filename']; 
                            ?>
                            
                            <div class="img-card <?php echo $isActive ? 'active' : ''; ?>">
                                <?php if($isActive): ?>
                                    <div class="status-badge">ACTIVE</div>
                                <?php endif; ?>

                                <img src="<?php echo $imgSrc; ?>" class="qr-preview" alt="QR Code" onerror="this.src='images/error-img.png'; this.alt='Img Not Found'">
                                
                                <div class="card-actions">
                                    <div style="display:flex; align-items:center; gap:8px;">
                                        <input name="upiid" type="radio" class="custom-radio" value="<?php echo $row['filename']; ?>" <?php if($isActive){echo "checked";} ?> />
                                        <span style="font-size:0.85rem; color:#555; font-weight:700;">Select</span>
                                    </div>

                                    <a href="addupiimg.php?delete=<?php echo $row['filename']; ?>" class="btn-delete" onclick="return confirm('⚠️ Delete this image permanently?');">
                                        <i class="fa-solid fa-trash-can"></i>
                                    </a>
                                </div>
                            </div>

                            <?php 
                                    } 
                                } else {
                                    echo '<div style="grid-column:1/-1; text-align:center; padding:40px; color:#aaa; font-weight:600;">No QR Codes Uploaded Yet</div>';
                                }
                            ?>
                        </div>

                        <button type="submit" class="btn-save-float">
                            <i class="fa-solid fa-check-double"></i> Save Active
                        </button>
                    </form>

                </div>
                
                <footer class="footer" style="padding:20px; text-align:center; color:#888; font-size:0.8rem;">
                    <span>© 2026 AB Coders</span>
                </footer>

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

    <script src="vendors/base/vendor.bundle.base.js"></script>
    <script src="js/off-canvas.js"></script>
    <script src="js/hoverable-collapse.js"></script>
    <script src="js/template.js"></script>
    <script src="vendors/chart.js/Chart.min.js"></script>
    <script src="js/dashboard.js"></script>

    <script>
    if (window.history.replaceState) {
        window.history.replaceState(null, null, window.location.href);
    }

    
    </script>
</body>
</html>