<?php
include("connection.php");

if (!isset($_REQUEST['id'])) {
    header('Location: photo.php');
    exit;
}

$id = intval($_REQUEST['id']);

// Fetch existing data
$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 = '';
$success_message = '';

if (isset($_POST['update'])) {
    $new_caption = trim($_POST['caption_text']);
    $new_page_name = $_POST['page_name'];
    $remove_requested = isset($_POST['remove_existing']) && $_POST['remove_existing'] == '1';
    $file = $_FILES['Image'];
    $file_name = $file['name'];
    $file_tmp = $file['tmp_name'];
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    $upload_dir = 'assets/images/gallery/';
    $old_file_path = $upload_dir . $photo;

    $image_exts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $video_exts = ['mp4', 'webm', 'ogg'];

    $new_photo = $photo;

    // Remove requested
    if ($remove_requested && file_exists($old_file_path)) {
        unlink($old_file_path);
        $new_photo = '';
    }

    // New file uploaded
    if (!empty($file_name)) {
        $allowed_exts = ($new_page_name === 'Image') ? $image_exts : $video_exts;

        if (!in_array($file_ext, $allowed_exts)) {
            $error_message = "Invalid file format for $new_page_name.";
        } else {
            $new_photo = strtolower($new_page_name) . "-" . $id . "-" . time() . "-" . uniqid() . "." . $file_ext;
            $new_path = $upload_dir . $new_photo;

            if (file_exists($old_file_path)) {
                unlink($old_file_path);
            }

            if (!move_uploaded_file($file_tmp, $new_path)) {
                $error_message = "Failed to upload the new file.";
            }

            if ($new_page_name === 'Video') {
                $new_caption = ''; // Reset caption for video
            }
        }
    }

    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_page_name, $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="../images/logo.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="old_image" value="<?php echo $photo; ?>">
                                            <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 ($page_name === 'Image' && !empty($photo)): ?>
                                                    <div class="media-wrapper">
                                                        <img id="previewImg" src="assets/images/gallery/<?php echo htmlspecialchars($photo); ?>" width="150" alt="Image">
                                                        <span class="remove-icon" onclick="removeMedia()">&#10006;</span>
                                                    </div>
                                                <?php elseif ($page_name === 'Video' && !empty($photo)): ?>
                                                    <div class="media-wrapper">
                                                        <video id="previewVideo" width="200" controls>
                                                            <source src="assets/images/gallery/<?php echo htmlspecialchars($photo); ?>" type="video/mp4">
                                                            Your browser does not support the video tag.
                                                        </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); ?>" placeholder="Enter caption..." />
                                                </div>
                                                <div class="col-lg-6">
                                                    <label class="form-label">Select Type <span>*</span></label>
                                                    <select class="form-control" name="page_name" id="type_selector">
                                                        <option value="Image" <?php if ($page_name == 'Image') echo 'selected'; ?>>Image</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"><button type="button" class="btn btn-danger">View Data</button></a>
                                            </div>
                                        </form>


                                    </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>