<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: admin_login.php");
    exit;
}


if (isset($_GET['logout'])) {
    session_destroy();
    header("location: admin_login.php");
    exit;
}


require_once '../config.php';
require_once '../get_setting.php'; 


$upload_dir = '../uploads/giveaway_images/';


$message = '';
$error = '';



function get_all_giveaways($pdo) {
    $sql = "SELECT * FROM giveaways ORDER BY id DESC";
    $stmt = $pdo->query($sql);
    return $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
}

function get_giveaway_by_id($pdo, $id) {
    $sql = "SELECT * FROM giveaways WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetch(PDO::FETCH_ASSOC);
}


if (!is_dir($upload_dir)) {
    if (!mkdir($upload_dir, 0777, true)) {
        $error = "CRITICAL ERROR: Failed to create upload directory. Check permissions.";
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_giveaway'])) {
    
   
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $value = trim($_POST['value']);
    $prize_name_short = trim($_POST['prize_name_short']);
    $giveaway_id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $current_image_url = $_POST['current_image_url'] ?? ''; 

    if (empty($title) || empty($description) || empty($value) || empty($prize_name_short)) {
        $error = "All text fields are required. Please check your input.";
    } elseif (strlen($title) > 255 || strlen($prize_name_short) > 50) {
        $error = "Title or Short Prize Name is too long.";
    }

    $image_url_to_save = $current_image_url; 

    // --- 2. Handle Image Upload ---
    if (isset($_FILES['image_file']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['image_file'];
        $file_name = $file['name'];
        $file_tmp = $file['tmp_name'];
        $file_size = $file['size'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        // Validation checks
        $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];
        if (!in_array($file_ext, $allowed_ext)) {
            $error = "Invalid file type. Only JPG, JPEG, PNG, and GIF are allowed.";
        } elseif ($file_size > 5000000) { 
            $error = "File size must be 5MB or less.";
        }

        if (empty($error)) {
            // Generate a unique file name
            $new_file_name = uniqid('giveaway_') . '.' . $file_ext;
            $destination = $upload_dir . $new_file_name;

            
            if (move_uploaded_file($file_tmp, $destination)) {
               
                $image_url_to_save = $destination;

                
                if ($giveaway_id > 0 && !empty($current_image_url) && $current_image_url !== $image_url_to_save && file_exists($current_image_url)) {
                    @unlink($current_image_url); 
                }
            } else {
                $error = "File upload failed. Check the upload directory permissions (should be 0777).";
            }
        }
    } elseif ($giveaway_id == 0 && empty($error)) {
       
        $error = "An image file is required for new giveaways.";
    }

    // --- 3. Execute Database Query ---
    if (empty($error)) {
        if ($giveaway_id > 0) {
            // Update existing giveaway
            $sql = "UPDATE giveaways SET title=:title, description=:description, image_url=:image_url, value=:value, prize_name_short=:prize_name_short WHERE id=:id";
            $message = "Giveaway updated successfully!";
        } else {
            // Add new giveaway
            $sql = "INSERT INTO giveaways (title, description, image_url, value, prize_name_short) VALUES (:title, :description, :image_url, :value, :prize_name_short)";
            $message = "New giveaway added successfully!";
        }

        if ($stmt = $pdo->prepare($sql)) {
            $stmt->bindParam(':title', $title);
            $stmt->bindParam(':description', $description);
            $stmt->bindParam(':image_url', $image_url_to_save); // Use the final image path
            $stmt->bindParam(':value', $value);
            $stmt->bindParam(':prize_name_short', $prize_name_short);
            if ($giveaway_id > 0) {
                $stmt->bindParam(':id', $giveaway_id, PDO::PARAM_INT);
            }
            
            if (!$stmt->execute()) {
                $error = "Database error: Could not save the giveaway.";
                $message = ''; 
            }
        }
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_giveaway'])) {
    $giveaway_id = (int)$_POST['id'];

   
    $giveaway_to_delete = get_giveaway_by_id($pdo, $giveaway_id);
    
  
    $sql = "DELETE FROM giveaways WHERE id = :id";
    if ($stmt = $pdo->prepare($sql)) {
        $stmt->bindParam(':id', $giveaway_id, PDO::PARAM_INT);
        if ($stmt->execute()) {
            $message = "Giveaway ID #{$giveaway_id} deleted successfully.";
            
           
            if ($giveaway_to_delete && !empty($giveaway_to_delete['image_url']) && file_exists($giveaway_to_delete['image_url'])) {
                 @unlink($giveaway_to_delete['image_url']); 
            }
        } else {
            $error = "Error deleting the giveaway record.";
        }
    }
}

// Determine if we are editing a giveaway
$editing_giveaway = null;
if (isset($_GET['edit_id']) && is_numeric($_GET['edit_id'])) {
    $editing_giveaway = get_giveaway_by_id($pdo, (int)$_GET['edit_id']);
    if (!$editing_giveaway) {
        $error = "Giveaway not found for editing.";
    }
}


$giveaways = get_all_giveaways($pdo);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Giveaways - LUX ADMIN</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <?php if ($use_favicon): ?>
    <link rel="icon" type="<?php echo $favicon_mime; ?>" href="../<?php echo $favicon_path; ?>">
    <?php endif; ?>
    <link href="https://fonts.googleapis.com/css2?family=Work+Sans:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        :root { --bs-crimson-faded: #b000001a; }
        .text-gold { color: #d4af37; }
        .form-control, .form-select { border-radius: 8px !important; border: 2px solid #e2e8f0 !Important; box-shadow: none; padding: 0.75rem .75rem !important; }
        .form-control:focus, .form-select:focus { border-color: var(--bs-crimson-light) !Important; box-shadow: 0 0 0 0.25rem var(--bs-crimson-faded) !important; }

        
        .image-preview-box {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            background-color: #f8f9fa;
            cursor: pointer;
            transition: border-color 0.3s;
        }
        .image-preview-box:hover {
            border-color: #aaa;
        }
        .image-preview {
            max-width: 100%;
            max-height: 200px;
            border-radius: 6px;
            display: none; 
            margin-top: 10px;
        }
    </style>
</head>
<body>

    <?php include "nav.php" ?>
    
    <div id="wrapper">
        <?php include "header.php" ?>
        
        <div class="main-content-wrapper">
            <div id="main-content" class="container-fluid">
                <h3 class="fw-bolder mb-4"><i class="bi bi-gift me-2"></i> Manage Giveaways</h3>
                
                <?php if ($message || $error): ?>
                    <script>
                        const Toast = Swal.mixin({
                            toast: true,
                            position: 'top-end',
                            showConfirmButton: false,
                            timer: 3000,
                            timerProgressBar: true
                        });
                        Toast.fire({
                            icon: '<?php echo $error ? "error" : "success"; ?>',
                            title: '<?php echo $error ?: $message; ?>'
                        });
                    </script>
                <?php endif; ?>

                <div class="row g-4">
                    
                    <div class="col-lg-12">
                        <div class="card-enhanced border-0 shadow">
                            <div class="card-header bg-white border-bottom fw-bold">
                                <?php echo $editing_giveaway ? 'Edit Giveaway: ' . htmlspecialchars($editing_giveaway['title']) : 'Add New Giveaway'; ?>
                            </div>
                            <div class="card-body p-4">
                                <form action="manage_giveaways.php" method="POST" enctype="multipart/form-data" class="needs-validation" novalidate>
                                    
                                    <?php if ($editing_giveaway): ?>
                                        <input type="hidden" name="id" value="<?php echo (int)$editing_giveaway['id']; ?>">
                                        <input type="hidden" name="current_image_url" value="<?php echo htmlspecialchars($editing_giveaway['image_url'] ?? ''); ?>">
                                    <?php endif; ?>
                                    <input type="hidden" name="submit_giveaway" value="1">

                                    <div class="mb-3">
                                        <label for="title" class="form-label">Prize Title (e.g., The Dream Home & $250K Cash)</label>
                                        <input type="text" class="form-control" id="title" name="title" required maxlength="255" value="<?php echo htmlspecialchars($editing_giveaway['title'] ?? ''); ?>">
                                        <div class="invalid-feedback">Please enter a title.</div>
                                    </div>

                                    <div class="mb-3">
                                        <label for="prize_name_short" class="form-label">Short Prize Name (Used in Entry Modal)</label>
                                        <input type="text" class="form-control" id="prize_name_short" name="prize_name_short" required maxlength="50" value="<?php echo htmlspecialchars($editing_giveaway['prize_name_short'] ?? ''); ?>">
                                        <div class="form-text">e.g., 'Dream Home' or '$50,000 Cash'</div>
                                        <div class="invalid-feedback">Please enter a short name.</div>
                                    </div>

                                    <div class="mb-3">
                                        <label for="description" class="form-label">Description</label>
                                        <textarea class="form-control" id="description" name="description" rows="3" required><?php echo htmlspecialchars($editing_giveaway['description'] ?? ''); ?></textarea>
                                        <div class="invalid-feedback">Please enter a description.</div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-8 mb-3">
                                            <label for="image_file" class="form-label">Prize Image (JPG, PNG, GIF, max 5MB)</label>
                                            
                                            <input class="form-control" type="file" id="image_file" name="image_file" accept=".jpg,.jpeg,.png,.gif" <?php echo $editing_giveaway ? '' : 'required'; ?>>
                                            <div class="form-text text-muted">
                                                <?php if ($editing_giveaway): ?>
                                                    Leave blank to keep the current image.
                                                <?php else: ?>
                                                    Upload a prize image.
                                                <?php endif; ?>
                                            </div>
                                            <div class="invalid-feedback">
                                                <?php echo $editing_giveaway ? 'Please select an image if you want to change it.' : 'Please select an image.'; ?>
                                            </div>
                                            
                                        </div>
                                        <div class="col-md-4 mb-3">
                                            <label for="value" class="form-label">Estimated Value</label>
                                            <input type="text" class="form-control" id="value" name="value" required maxlength="100" value="<?php echo htmlspecialchars($editing_giveaway['value'] ?? ''); ?>">
                                            <div class="form-text">e.g., '$1,500,000+' or 'Market Price'</div>
                                            <div class="invalid-feedback">Please enter the estimated value.</div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Image Preview</label>
                                        <div class="image-preview-box" onclick="document.getElementById('image_file').click();">
                                            <p class="text-muted mb-0"><i class="bi bi-cloud-upload-fill fs-4 me-2"></i>Click to select image</p>
                                            <img id="image_preview" class="image-preview" 
                                                 src="<?php echo $editing_giveaway && !empty($editing_giveaway['image_url']) ? htmlspecialchars($editing_giveaway['image_url']) : ''; ?>"
                                                 style="<?php echo $editing_giveaway && !empty($editing_giveaway['image_url']) ? 'display: block; margin: 10px auto 0 auto;' : 'display: none;'; ?>"
                                                 alt="Image Preview">
                                            <?php if ($editing_giveaway && !empty($editing_giveaway['image_url'])): ?>
                                                <p class="text-success small mt-2 mb-0" id="current_image_status">Current image loaded.</p>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    
                                    <div class="d-flex justify-content-between align-items-center mt-3">
                                        <button type="submit" class="btn btn-crimson fw-bold">
                                            <i class="bi bi-save me-1"></i> <?php echo $editing_giveaway ? 'Save Changes' : 'Create Giveaway'; ?>
                                        </button>
                                        <?php if ($editing_giveaway): ?>
                                            <a href="manage_giveaways.php" class="btn btn-outline-secondary">
                                                <i class="bi bi-x-circle me-1"></i> Cancel Edit
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-12">
                        <div class="card-enhanced border-0 shadow">
                            <div class="card-header bg-white border-bottom fw-bold fs-5">Current Active Giveaways (<?php echo count($giveaways); ?>)</div>
                            <div class="card-body p-0">
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Image</th>
                                                <th>Prize Title</th>
                                                <th>Value</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (!empty($giveaways)): ?>
                                                <?php foreach ($giveaways as $g): ?>
                                                    <tr>
                                                        <td><?php echo (int)$g['id']; ?></td>
                                                        <td>
                                                            <?php if (!empty($g['image_url']) && file_exists($g['image_url'])): ?>
                                                                <img src="<?php echo htmlspecialchars($g['image_url']); ?>" alt="Prize Image" style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px;">
                                                            <?php else: ?>
                                                                <i class="bi bi-image-fill text-danger fs-4"></i>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td class="fw-medium">
                                                            <?php echo htmlspecialchars($g['title']); ?><br>
                                                            <span class="small text-muted"><?php echo htmlspecialchars($g['prize_name_short']); ?></span>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($g['value']); ?></td>
                                                        <td>
														<div class ="d-inline-flex align-items-center">
                                                            <a href="?edit_id=<?php echo (int)$g['id']; ?>" class="btn btn-sm btn-outline-primary me-2" title="Edit">
                                                                <i class="bi bi-pencil-square"></i>
                                                            </a>
                                                            <form action="manage_giveaways.php" method="POST" class="d-inline delete-giveaway-form">
                                                                <input type="hidden" name="id" value="<?php echo (int)$g['id']; ?>">
                                                                <input type="hidden" name="delete_giveaway" value="1">
                                                                <button type="button" class="btn btn-sm btn-outline-danger delete-btn" title="Delete" data-id="<?php echo (int)$g['id']; ?>">
                                                                    <i class="bi bi-trash"></i>
                                                                </button>
                                                            </form>
														</div>	
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="5" class="text-center p-4">No giveaways have been added yet.</td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                </div> </div>
        </div>
    </div>
    
    <footer class="dashboard_footer">
        <div class="container-fluid">&copy; <?php echo date("Y"); ?> LUX Admin Dashboard. All Rights Reserved.</div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
           
            const imageFile = document.getElementById('image_file');
            const imagePreview = document.getElementById('image_preview');
            const currentImageStatus = document.getElementById('current_image_status');

            imageFile.addEventListener('change', function() {
                if (this.files && this.files[0]) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        imagePreview.src = e.target.result;
                        imagePreview.style.display = 'block';
                        if (currentImageStatus) {
                            currentImageStatus.textContent = 'New image selected.';
                            currentImageStatus.classList.remove('text-success');
                            currentImageStatus.classList.add('text-primary');
                        }
                    }
                    reader.readAsDataURL(this.files[0]);
                } else {
                   
                    imagePreview.style.display = 'none';
                    imagePreview.src = '';
                }
            });

            
            (function () {
                'use strict'
                var forms = document.querySelectorAll('.needs-validation')
                Array.prototype.slice.call(forms)
                    .forEach(function (form) {
                        form.addEventListener('submit', function (event) {
                            
                            const idField = document.getElementById('id');
                            const imageField = document.getElementById('image_file');
                            
                            if (!idField && imageField && !imageField.files.length) {
                                imageField.setCustomValidity('Image is required for new giveaways.');
                            } else {
                                if (imageField) imageField.setCustomValidity('');
                            }
                            
                            if (!form.checkValidity()) {
                                event.preventDefault()
                                event.stopPropagation()
                            }
                            form.classList.add('was-validated')
                        }, false)
                    })
            })()
        });

        document.querySelectorAll('.delete-btn').forEach(button => {
            button.addEventListener('click', function() {
                const form = this.closest('form');
                const id = this.getAttribute('data-id');
                Swal.fire({
                    title: 'Are you sure?',
                    text: `WARNING: Are you sure you want to delete giveaway #${id} and its image file?`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#B00000',
                    cancelButtonColor: '#6c757d',
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'Cancel',
                    background: '#fff',
                    borderRadius: '16px'
                }).then((result) => {
                    if (result.isConfirmed) {
                        form.submit();
                    }
                })
            });
        });
    </script>
</body>
</html>