<?php
include("connection.php");

if (!isset($_REQUEST['id'])) {
    header('Location: viewgallery.php');
    exit;
}

$id = intval($_REQUEST['id']);

// Fetch existing record
$stmt = $con->prepare("SELECT * FROM media WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$media = $result->fetch_assoc();

if (!$media) {
    echo "Record not found";
    exit;
}

$page_name = $media['page_name'];
$caption   = $media['caption'];
$photo     = $media['photo'];

$error_message = "";
$upload_dir = "assets/images/gallery/";
$existing_path = $upload_dir . $photo;

// Allowed file formats
$image_exts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$video_exts = ['mp4', 'webm', 'ogg'];

if (isset($_POST['update'])) {

    $new_caption = trim($_POST['caption_text']);
    $new_type    = $_POST['page_name'];
    $remove      = isset($_POST['remove_existing']) && $_POST['remove_existing'] == "1";

    $file_name = $_FILES['Image']['name'];
    $tmp_file  = $_FILES['Image']['tmp_name'];
    $ext       = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    $new_photo = $photo; // default keep same

    // ---------------------------
    // REMOVE EXISTING MEDIA
    // ---------------------------
    if ($remove && !empty($photo) && file_exists($existing_path)) {
        unlink($existing_path);
        $new_photo = "";
    }

    // ---------------------------
    // FILE UPLOADED
    // ---------------------------
    if (!empty($file_name)) {

        if ($new_type == "Manufacturing" || $new_type == "Project") {
            $allowed = $image_exts;
        } elseif ($new_type == "Video") {
            $allowed = $video_exts;
        } else {
            $allowed = $image_exts;
        }

        if (!in_array($ext, $allowed)) {
            $error_message = "Invalid file format for selected type.";
        } else {

            // delete old file if exists
            if (!empty($photo) && file_exists($existing_path)) {
                unlink($existing_path);
            }

            // new filename
            $new_photo = strtolower($new_type) . "-" . time() . "-" . uniqid() . "." . $ext;
            $new_path  = $upload_dir . $new_photo;

            if (!move_uploaded_file($tmp_file, $new_path)) {
                $error_message = "Failed to upload file.";
            }

            // If video uploaded → clear caption
            if ($new_type == "Video") {
                $new_caption = "";
            }
        }
    }

    // ---------------------------
    // UPDATE DATABASE
    // ---------------------------
    if (empty($error_message)) {

        $stmt = $con->prepare("UPDATE media SET caption=?, photo=?, page_name=? WHERE id=?");
        $stmt->bind_param("sssi", $new_caption, $new_photo, $new_type, $id);
        $stmt->execute();

        header("Location: viewgallery.php");
        exit;
    }
}
?>



<?php
include("header.php")
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title> certificate Update</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta content="Premium Multipurpose Admin & Dashboard Template" name="description" />
    <meta content="Themesbrand" name="author" />
    <!-- App favicon -->
    <!-- <link rel="shortcut icon" href="assets/images/favicon.ico" /> -->

    <!-- Plugins css -->
    <link href="assets/libs/dropzone/dropzone.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css">
    <link rel="shortcut icon" href="./assets/logo/fav.png" />

    <!-- Bootstrap Css -->
    <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
    <!-- Icons Css -->
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <!-- App Css-->
    <link href="assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
    <!-- App js -->
    <!-- <script src="assets/js/plugin.js"></script> -->
    <style>
        .form .input {
            width: 100%;
            background: white;
            border: none;
            padding: 15px 20px;
            border-radius: 20px;
            margin-bottom: 9px;
            margin-top: 15px;
            box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
            border-inline: 2px solid transparent;
        }

        input[name='Image'] {
            display: none;
        }

        .dropzone {
            border: 2px dashed #ccc;
            padding: 30px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
        }

        .dz-message i {
            font-size: 40px;
            color: #999;
        }

        .media-wrapper {
            position: relative;
            display: inline-block;
            margin-top: 10px;
        }

        .remove-icon {
            position: absolute;
            top: -10px;
            right: -10px;
            background-color: red;
            color: white;
            font-weight: bold;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            text-align: center;
            line-height: 24px;
            cursor: pointer;
            box-shadow: 0 0 3px #000;
            z-index: 10;
        }

        #media-preview img,
        #media-preview video {
            display: block;
        }
    </style>

</head>

<body data-sidebar="dark">
    <!-- <body data-layout="horizontal" data-topbar="dark"> -->

    <!-- Begin page -->
    <div id="layout-wrapper">

        <div class="w-80 ">
            <div class="page-content" style="width: 80%;margin-left: 260px;">
                <div class="container">
                    <!-- start page title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0 font-size-18"> certificate Update</h4>


                            </div>
                        </div>
                    </div>
                    <!-- end page title -->

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">

                                    <div>
                                        <form class="form" action="" method="POST" enctype="multipart/form-data">
                                            <input type="hidden" name="remove_existing" id="remove_existing" value="0">

                                            <div class="dropzone" id="upload">
                                                <div class="dz-message needsclick">
                                                    <div class="mb-3">
                                                        <i class="display-4 text-muted bx bxs-cloud-upload"></i>
                                                    </div>
                                                    <h4>Drop files here or click to upload</h4>
                                                </div>
                                                <input type="file" name="Image" id="imageInput" />
                                            </div>

                                            <div id="media-preview" class="mb-3">
                                                <?php if (!empty($photo) && ($page_name == 'Manufacturing' || $page_name == 'Project')): ?>
                                                    <div class="media-wrapper">
                                                        <img src="assets/images/gallery/<?php echo htmlspecialchars($photo); ?>" width="150">
                                                        <span class="remove-icon" onclick="removeMedia()">&#10006;</span>
                                                    </div>

                                                <?php elseif (!empty($photo) && $page_name == 'Video'): ?>
                                                    <div class="media-wrapper">
                                                        <video width="200" controls>
                                                            <source src="assets/images/gallery/<?php echo htmlspecialchars($photo); ?>">
                                                        </video>
                                                        <span class="remove-icon" onclick="removeMedia()">&#10006;</span>
                                                    </div>

                                                <?php else: ?>
                                                    <p>No media available.</p>
                                                <?php endif; ?>
                                            </div>

                                            <div class="row mt-3">
                                                <div class="col-lg-6">
                                                    <label class="form-label">Caption / Video URL</label>
                                                    <input type="text" class="form-control" name="caption_text" value="<?php echo htmlspecialchars($caption); ?>">
                                                </div>

                                                <div class="col-lg-6">
                                                    <label class="form-label">Select Type *</label>
                                                    <select class="form-control" name="page_name">
                                                        <option value="Manufacturing" <?php if ($page_name == 'Manufacturing') echo 'selected'; ?>>Manufacturing</option>
                                                        <option value="Project" <?php if ($page_name == 'Project') echo 'selected'; ?>>Project</option>
                                                        <option value="Video" <?php if ($page_name == 'Video') echo 'selected'; ?>>Video</option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="text-center mt-4">
                                                <input type="submit" name="update" class="btn btn-primary" value="Submit" />
                                                <a href="viewgallery.php" class="btn btn-danger">View Data</a>
                                            </div>
                                        </form>

                                        <script>
                                            function removeMedia() {
                                                document.getElementById('remove_existing').value = "1";
                                                document.getElementById('media-preview').innerHTML = "<p>Existing media removed.</p>";
                                            }
                                        </script>



                                    </div>

                                </div>
                            </div>
                        </div>
                        <!-- end col -->
                    </div>
                    <!-- end row -->
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->


        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->




    <!-- JAVASCRIPT -->
    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/libs/metismenu/metisMenu.min.js"></script>
    <script src="assets/libs/simplebar/simplebar.min.js"></script>
    <script src="assets/libs/node-waves/waves.min.js"></script>

    <!-- Plugins js -->
    <script src="assets/libs/dropzone/dropzone-min.js"></script>

    <!-- Form file upload init js -->
    <script src="assets/js/pages/form-file-upload.init.js"></script>

    <script src="assets/js/app.js"></script>
    <script>
        const imgInput = document.getElementById("imageInput");
        const uploadBox = document.getElementById("upload");
        const removeExistingInput = document.getElementById("remove_existing");

        uploadBox.onclick = () => imgInput.click();

        imgInput.onchange = () => {
            const file = imgInput.files[0];
            if (!file) return;

            const fileURL = URL.createObjectURL(file);
            const fileType = file.type;
            const previewContainer = document.getElementById("media-preview");
            previewContainer.innerHTML = ''; // Clear old preview

            const wrapper = document.createElement("div");
            wrapper.classList.add("media-wrapper");

            const removeIcon = document.createElement("span");
            removeIcon.classList.add("remove-icon");
            removeIcon.innerHTML = "&#10006;";
            removeIcon.onclick = removeMedia;

            if (fileType.startsWith('image/')) {
                const img = document.createElement("img");
                img.src = fileURL;
                img.width = 150;
                img.alt = "Preview Image";
                wrapper.appendChild(img);
            } else if (fileType.startsWith('video/')) {
                const video = document.createElement("video");
                video.width = 200;
                video.controls = true;
                const source = document.createElement("source");
                source.src = fileURL;
                source.type = fileType;
                video.appendChild(source);
                wrapper.appendChild(video);
            }

            wrapper.appendChild(removeIcon);
            previewContainer.appendChild(wrapper);

            removeExistingInput.value = '0'; // Reset remove flag
        };

        function removeMedia() {
            const previewContainer = document.getElementById("media-preview");
            previewContainer.innerHTML = '<p>No media selected.</p>';
            removeExistingInput.value = '1';
            imgInput.value = ''; // Clear input so it doesn't upload the file
        }
    </script>



    <?php
    include("footer.php")
    ?>
</body>

</html>