<?php
include("connection.php");
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

$error_message = '';
$success_message = '';

if (isset($_POST['form1'])) {
    $page_name = $_POST['page_name'];
    $caption = trim($_POST['caption']);

    $allowed_image_exts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $allowed_video_exts = ['mp4', 'webm', 'ogg',];

    $files = $_FILES['photo'];
    $total = count($files['name']);
    $upload_success = false;

    for ($i = 0; $i < $total; $i++) {
        $file_name = $files['name'][$i];
        $file_tmp = $files['tmp_name'][$i];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $timestamp = date('YmdHis');
        $unique_id = uniqid();

        if (empty($file_name)) continue;

        // Handle Images
        if ($page_name === 'Image') {
            if (!in_array($file_ext, $allowed_image_exts)) {
                $error_message .= "Invalid image format: $file_name<br>";
                continue;
            }

            $new_name = 'image-' . $timestamp . '-' . $unique_id . '.' . $file_ext;
            $upload_path = 'assets/images/gallery/' . $new_name;

            if (move_uploaded_file($file_tmp, $upload_path)) {
                $stmt = $con->prepare("INSERT INTO media (caption, photo, page_name, created_at) VALUES (?, ?, ?, ?)");
                $created_at = date('Y-m-d H:i:s');
                $stmt->bind_param("ssss", $caption, $new_name, $page_name, $created_at);
                $stmt->execute();
                $upload_success = true;
            } else {
                $error_message .= "Failed to move uploaded image: $file_name<br>";
            }

        }
        // Handle Videos
        elseif ($page_name === 'Video') {
            if (!in_array($file_ext, $allowed_video_exts)) {
                $error_message .= "Invalid video format: $file_name<br>";
                continue;
            }

            $new_video = 'video-' . $timestamp . '-' . $unique_id . '.' . $file_ext;
            $upload_path = 'assets/images/gallery/' . $new_video;

            if (move_uploaded_file($file_tmp, $upload_path)) {
                $stmt = $con->prepare("INSERT INTO media (caption, photo, page_name, created_at) VALUES (?, ?, ?, ?)");
                $created_at = date('Y-m-d H:i:s');
                $stmt->bind_param("ssss", $caption, $new_video, $page_name, $created_at);
                $stmt->execute();
                $upload_success = true;
            } else {
                $error_message .= "Failed to move uploaded video: $file_name<br>";
            }
        }
    }

    // Optional: If only caption for video (no file)
    if ($page_name === 'Video' && !$upload_success && !empty($caption)) {
        $stmt = $con->prepare("INSERT INTO media (caption, photo, page_name, created_at) VALUES (?, '', ?, ?)");
        $created_at = date('Y-m-d H:i:s');
        $stmt->bind_param("sss", $caption, $page_name, $created_at);
        $stmt->execute();
        $upload_success = true;
    }

    if ($upload_success) {
        header("Location: viewgallery.php");
        exit;
    } else {
        $error_message .= "No valid files were uploaded.<br>";
    }
}
?>




<?php
include("header.php")
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>ADD gallery/videos</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">

    <!-- Bootstrap Css -->
    <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
    <link rel="shortcut icon" href="./assets/logo/fav.png" />
    <!-- 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.form {
            /* background: white; */
            /* padding: 30px; */
            border-radius: 15px;
            /* box-shadow: 0 0 20px rgba(0, 0, 0, 0.1); */
            width: 100%;
            margin: auto;
        }

        .dropzone {
            position: relative;
            border: 2px dashed #d0d0d0;
            border-radius: 10px;
            padding: 40px 20px;
            text-align: center;
            cursor: pointer;
            background: #f9f9f9;
        }

        /* .dropzone:hover {
            background: #f1f1f1;
        } */

        .dropzone input[type="file"] {
            position: absolute;
            width: 100%;
            height: 100%;
            opacity: 0;
            top: 0;
            left: 0;
            cursor: pointer;
        }

        .dz-message {
            color: #777;
            font-size: 16px;
        }

        .dz-message i {
            font-size: 40px;
            margin-bottom: 10px;
        }

        .preview-container {
            margin-top: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
        }

        .preview-container div {
            display: inline-block;
            position: relative;
            margin: 10px;
        }

        .preview-container img {
            max-width: 150px;
            max-height: 150px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .preview-container button {
            position: absolute;
            top: 0;
            right: 0;
            background: red;
            color: white;
            border: none;
            border-radius: 50%;
            width: 25px;
            height: 25px;
            cursor: pointer;
        }
    </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"> ADD gallery / videos</h4>


                            </div>
                        </div>
                    </div>
                    <!-- end page title -->

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">

                                    <div>
                                        <?php if (!empty($error_message)): ?>
                                            <div style="color: red;"><?php echo $error_message; ?></div>
                                        <?php endif; ?>

                                        <?php if (!empty($success_message)): ?>
                                            <div style="color: green;"><?php echo $success_message; ?></div>
                                        <?php endif; ?>

                                        <form class="form" action="" method="POST" enctype="multipart/form-data">
                                            <input type="hidden" name="form1" value="1">

                                            <div class="dropzone" id="dropzone">
                                                <input type="file" name="photo[]" id="imageInput" multiple />
                                                <div class="dz-message">
                                                    <i class="bx bxs-cloud-upload"></i>
                                                    <h4>Click or Drop Files Here to Upload</h4>
                                                </div>
                                            </div>

                                            <div class="preview-container" id="previewContainer"></div>

                                            <div class="row">
                                                <div class="col-lg-6">
                                                     <label class="form-label" >Caption / Video URL</label>
                                                    <input type="text" class="form-control" name="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">Image</option>
                                                        <option value="Video">Video</option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="text-center mt-4">
                                                <button type="submit" name="form1" class="btn btn-primary">Submit</button>
                                                <a href="viewgallery.php" class="btn btn-danger">View Data</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 imageInput = document.getElementById('imageInput');
    const previewContainer = document.getElementById('previewContainer');
    let selectedFiles = [];

    imageInput.addEventListener('change', function () {
        selectedFiles = Array.from(this.files);
        updatePreview();
    });

    function updatePreview() {
        previewContainer.innerHTML = '';

        selectedFiles.forEach((file, index) => {
            const wrapper = document.createElement('div');
            wrapper.style.position = 'relative';
            wrapper.style.display = 'inline-block';
            wrapper.style.margin = '10px';
            wrapper.style.border = '1px solid #ccc';
            wrapper.style.padding = '5px';
            wrapper.style.borderRadius = '6px';
            wrapper.style.backgroundColor = '#f8f8f8';

            const removeBtn = document.createElement('button');
            removeBtn.textContent = '×';
            removeBtn.style.position = 'absolute';
            removeBtn.style.top = '-8px';
            removeBtn.style.right = '-8px';
            removeBtn.style.background = 'red';
            removeBtn.style.color = 'white';
            removeBtn.style.border = 'none';
            removeBtn.style.borderRadius = '50%';
            removeBtn.style.cursor = 'pointer';
            removeBtn.style.width = '22px';
            removeBtn.style.height = '22px';
            removeBtn.style.fontSize = '14px';
            removeBtn.onclick = () => {
                selectedFiles.splice(index, 1);
                updatePreview();
                updateFileInput();
            };

            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.style.maxWidth = '150px';
                    img.style.maxHeight = '150px';
                    img.style.display = 'block';
                    wrapper.appendChild(img);
                    wrapper.appendChild(removeBtn);
                    previewContainer.appendChild(wrapper);
                };
                reader.readAsDataURL(file);
            } else if (file.type.startsWith('video/')) {
                const video = document.createElement('video');
                video.src = URL.createObjectURL(file);
                video.controls = true;
                video.style.maxWidth = '150px';
                video.style.maxHeight = '150px';
                wrapper.appendChild(video);
                wrapper.appendChild(removeBtn);
                previewContainer.appendChild(wrapper);
            }
        });
    }

    function updateFileInput() {
        const dataTransfer = new DataTransfer();
        selectedFiles.forEach(file => dataTransfer.items.add(file));
        imageInput.files = dataTransfer.files;
    }
</script>



    <!-- <script>
        const imageInput = document.getElementById('imageInput');
        const previewContainer = document.getElementById('previewContainer');

        imageInput.addEventListener('change', function() {
            previewContainer.innerHTML = ''; 

            Array.from(this.files).forEach(file => {
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        previewContainer.appendChild(img);
                    }
                    reader.readAsDataURL(file);
                }
            });
        });
    </script> -->
    <?php
    include("footer.php")
    ?>
</body>


</html>