<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';


// --- Page-Specific Logic Starts Here ---

// 2. INITIALIZE VARIABLES & DETERMINE MODE (ADD/EDIT)
$edit_mode = false;
$service = []; // Initialize empty array to prevent errors in 'add' mode
$page_error = '';

$item_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($item_id) {
    $edit_mode = true;
}

// 3. FETCH DATA FOR FORM IF EDITING
if ($edit_mode) {
    // We also check for category='Service' to ensure we're editing the right item type
    $stmt = $conn->prepare("SELECT * FROM tours WHERE id = ? AND category = 'Service'");
    $stmt->bind_param("i", $item_id);
    $stmt->execute();
    $service = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if (!$service) {
        $page_error = "The requested service could not be found.";
    }
}

// 4. HANDLE FORM SUBMISSION (CREATE OR UPDATE)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect and sanitize data
    $title = trim($_POST['title']);
    $location = trim($_POST['location']);
    $price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);
    $status = isset($_POST['status']) ? 'published' : 'draft';
    $description = $_POST['description']; // Assuming TinyMCE cleans its own output
    
    // Handle file upload
    $image_url = $_POST['current_image_url'] ?? ''; // Keep old image by default
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/services/';
        if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }
        $filename = uniqid() . '-' . basename($_FILES['image']['name']);
        $target_path = $upload_dir . $filename;
        if (move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
            $image_url = 'uploads/services/' . $filename;
        } else {
            $_SESSION['error_message'] = "Error uploading file.";
        }
    }

    if (empty($title) || empty($location)) {
        $_SESSION['error_message'] = "Service Title and Location are required.";
    } else {
        if ($edit_mode) { // UPDATE
            $stmt = $conn->prepare("UPDATE tours SET title=?, location=?, price=?, status=?, description=?, image_url=? WHERE id=? AND category = 'Service'");
            $stmt->bind_param("ssdsssi", $title, $location, $price, $status, $description, $image_url, $item_id);
            if($stmt->execute()) $_SESSION['success_message'] = "Service updated successfully."; else $_SESSION['error_message'] = "Error updating service.";
            $stmt->close();
        } else { // INSERT
            $category = 'Service';
            $stmt = $conn->prepare("INSERT INTO tours (category, title, location, price, status, description, image_url) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssdsis", $category, $title, $location, $price, $status, $description, $image_url);
            if($stmt->execute()) $_SESSION['success_message'] = "Service created successfully."; else $_SESSION['error_message'] = "Error creating service.";
            $stmt->close();
        }
        header("Location: manage-services.php");
        exit();
    }
}


// 5. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<script src="https://cdn.tiny.cloud/1/<?php echo htmlspecialchars($settings['api_tinymce'] ?? 'no-api-key'); ?>/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: 'textarea#description',
    plugins: 'code table lists link autoresize',
    toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright | bullist numlist | code | table | link',
    skin: (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'oxide-dark' : 'oxide'),
    content_css: (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default'),
    height: 300
  });
</script>

<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<?php if ($page_error): ?>
    <div class="alert alert-danger mt-4"><h4 class="alert-heading">Error</h4><p><?php echo $page_error; ?></p><hr><a href="manage-services.php" class="btn btn-outline-danger">Return to Services List</a></div>
<?php else: ?>
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <div>
            <h1 class="h2"><?php echo $edit_mode ? 'Edit Service' : 'Add New Service'; ?></h1>
            <nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="manage-services.php">Services</a></li><li class="breadcrumb-item active"><?php echo $edit_mode ? htmlspecialchars($service['title']) : 'New'; ?></li></ol></nav>
        </div>
    </div>
    
    <form method="POST" action="edit-service.php<?php echo $edit_mode ? '?id=' . $item_id : ''; ?>" enctype="multipart/form-data">
        <div class="row g-4">
            <div class="col-lg-8">
                <div class="card shadow-sm">
                    <div class="card-body">
                        <div class="mb-3"><label class="form-label">Service Title <span class="text-danger">*</span></label><input type="text" class="form-control" name="title" value="<?php echo htmlspecialchars($service['title'] ?? ''); ?>" required></div>
                        <div class="mb-3"><label class="form-label">Description</label><textarea id="description" name="description" rows="10"><?php echo htmlspecialchars($service['description'] ?? ''); ?></textarea></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card shadow-sm">
                    <div class="card-header"><strong>Attributes</strong></div>
                    <div class="card-body">
                        <div class="mb-3"><label class="form-label">Location <span class="text-danger">*</span></label><input type="text" class="form-control" name="location" value="<?php echo htmlspecialchars($service['location'] ?? ''); ?>" required></div>
                        <div class="mb-3"><label class="form-label">Price</label><div class="input-group"><span class="input-group-text">₱</span><input type="number" step="0.01" class="form-control" name="price" value="<?php echo htmlspecialchars($service['price'] ?? '0.00'); ?>"></div></div>
                        <div class="form-check form-switch"><input class="form-check-input" type="checkbox" role="switch" id="status" name="status" <?php if(isset($service['status']) && $service['status'] == 'published') echo 'checked'; ?>><label class="form-check-label" for="status">Published (Visible on site)</label></div>
                    </div>
                </div>
                <div class="card shadow-sm mt-4">
                    <div class="card-header"><strong>Featured Image</strong></div>
                    <div class="card-body">
                        <input class="form-control" type="file" name="image" id="main-image-input">
                        <input type="hidden" name="current_image_url" value="<?php echo htmlspecialchars($service['image_url'] ?? ''); ?>">
                        <?php $image_src = !empty($service['image_url']) ? '../' . htmlspecialchars($service['image_url']) : 'https://via.placeholder.com/300x200.png?text=No+Image'; ?>
                        <img id="image-preview" src="<?php echo $image_src; ?>" class="img-fluid rounded border mt-2" alt="Image Preview">
                    </div>
                </div>
            </div>
        </div>
        <div class="mt-4 d-flex justify-content-end gap-2">
            <a href="manage-services.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle-fill me-1"></i> <?php echo $edit_mode ? 'Update Service' : 'Save Service'; ?></button>
        </div>
    </form>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const imageInput = document.getElementById('main-image-input');
    const imagePreview = document.getElementById('image-preview');
    if (imageInput) {
        imageInput.addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const reader = new FileReader();
                reader.onload = function(event) { imagePreview.src = event.target.result; }
                reader.readAsDataURL(e.target.files[0]);
            }
        });
    }
});
</script>

<?php include 'admin-footer.php'; ?>
