<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/gallery.php';
require_once __DIR__ . '/../app/marketing.php';

$user = sparrow_require_backyard_login();

$item_id = (int) ($_GET['id'] ?? 0);
$item = $item_id > 0 ? sparrow_get_gallery_item($item_id) : null;

if ($item_id > 0 && !$item) {
    sparrow_backyard_header('Gallery Item Not Found');
    ?>

    <section class="card">
        <h1>Gallery Item Not Found</h1>
        <p class="muted">That gallery item could not be found.</p>

        <a class="button" href="<?php echo sparrow_escape(sparrow_url('/backyard/gallery.php')); ?>">
            Back to Gallery
        </a>
    </section>

    <?php
    sparrow_backyard_footer();
    exit;
}

$notice = '';
$error = '';

function sparrow_store_gallery_uploaded_file(string $tmp_name, string $original_name, int $gallery_item_id): ?string
{
    if ($tmp_name === '' || $original_name === '') {
        return null;
    }

    if (!is_uploaded_file($tmp_name)) {
        return null;
    }

    $upload_dir = dirname(__DIR__) . '/storage/gallery/';

    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed, true)) {
        return null;
    }

    $file_name = 'gallery-' . $gallery_item_id . '-' . time() . '-' . bin2hex(random_bytes(4)) . '.' . $ext;
    $destination = $upload_dir . $file_name;

    if (!move_uploaded_file($tmp_name, $destination)) {
        return null;
    }

    return '/storage/gallery/' . $file_name;
}

function sparrow_handle_gallery_uploads(int $gallery_item_id, string $title): void
{
    if (empty($_FILES['gallery_images']['name'][0])) {
        return;
    }

    $existing_images = sparrow_get_gallery_item_images($gallery_item_id);
    $has_primary = !empty($existing_images);

    foreach ($_FILES['gallery_images']['name'] as $index => $original_name) {
        if (empty($original_name)) {
            continue;
        }

        $tmp_name = $_FILES['gallery_images']['tmp_name'][$index] ?? '';
        $error_code = $_FILES['gallery_images']['error'][$index] ?? UPLOAD_ERR_NO_FILE;

        if ($error_code !== UPLOAD_ERR_OK) {
            continue;
        }

        $image_path = sparrow_store_gallery_uploaded_file($tmp_name, $original_name, $gallery_item_id);

        if ($image_path) {
            $is_primary = !$has_primary;

            sparrow_add_gallery_image($gallery_item_id, $image_path, $title, $is_primary);

            $has_primary = true;
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save_gallery_item') {
        try {
            $saved_id = sparrow_save_gallery_item([
                'title' => $_POST['title'] ?? '',
                'category' => $_POST['category'] ?? '',
                'description' => $_POST['description'] ?? '',
                'featured' => $_POST['featured'] ?? '',
                'show_public' => $_POST['show_public'] ?? '',
                'status' => $_POST['status'] ?? 'Published',
                'sort_order' => $_POST['sort_order'] ?? 0,
            ], $item_id);

            sparrow_handle_gallery_uploads($saved_id, trim($_POST['title'] ?? ''));

$save_mode = $_POST['save_mode'] ?? 'save_stay';

if ($save_mode === 'save_add_another') {
    sparrow_redirect('/backyard/gallery-edit.php?added=1');
}

sparrow_redirect('/backyard/gallery-edit.php?id=' . $saved_id . '&saved=1');
        } catch (Throwable $e) {
            $error = $e->getMessage();
        }
    }
	
	    if ($action === 'create_marketing_post') {
        try {
            if ($item_id <= 0) {
                throw new RuntimeException('Save the gallery item before creating a marketing post.');
            }

            $current_item = sparrow_get_gallery_item($item_id);

            if (!$current_item) {
                throw new RuntimeException('Gallery item could not be found.');
            }

            $images = sparrow_get_gallery_item_images($item_id);
            $primary_image_path = '';

            if (!empty($images[0]['image_path'])) {
                $primary_image_path = $images[0]['image_path'];
            }

            $marketing_post_id = sparrow_create_marketing_post_from_gallery_item($current_item, $primary_image_path);

            sparrow_redirect('/backyard/marketing-edit.php?id=' . $marketing_post_id . '&from_gallery=1');
        } catch (Throwable $e) {
            $error = $e->getMessage();
        }
    }
	
	    if ($action === 'upload_more_images') {
        try {
            if ($item_id > 0) {
                $current_item = sparrow_get_gallery_item($item_id);

                if ($current_item) {
                    sparrow_handle_gallery_uploads($item_id, $current_item['title'] ?? '');
                    sparrow_redirect('/backyard/gallery-edit.php?id=' . $item_id . '&photos_added=1');
                }
            }
        } catch (Throwable $e) {
            $error = 'Photos could not be uploaded.';
        }
    }

    if ($action === 'update_image_details') {
        $image_id = (int) ($_POST['image_id'] ?? 0);
        $alt_text = $_POST['alt_text'] ?? '';
        $sort_order = (int) ($_POST['sort_order'] ?? 0);

        try {
            if ($image_id > 0) {
                sparrow_update_gallery_image_details($image_id, $alt_text, $sort_order);
                $notice = 'Image details saved.';
            }
        } catch (Throwable $e) {
            $error = 'Image details could not be saved.';
        }
    }

    if ($action === 'replace_image') {
        $image_id = (int) ($_POST['image_id'] ?? 0);

        try {
            if ($image_id > 0 && !empty($_FILES['replace_image']['name'])) {
                $tmp_name = $_FILES['replace_image']['tmp_name'] ?? '';
                $original_name = $_FILES['replace_image']['name'] ?? '';
                $error_code = $_FILES['replace_image']['error'] ?? UPLOAD_ERR_NO_FILE;

                if ($error_code === UPLOAD_ERR_OK) {
                    $image_path = sparrow_store_gallery_uploaded_file($tmp_name, $original_name, $item_id);

                    if ($image_path) {
                        sparrow_replace_gallery_image_path($image_id, $image_path);
                        $notice = 'Image replaced.';
                    }
                }
            }
        } catch (Throwable $e) {
            $error = 'Image could not be replaced.';
        }
    }

    if ($action === 'delete_image') {
        $image_id = (int) ($_POST['image_id'] ?? 0);

        try {
            if ($image_id > 0) {
                sparrow_delete_gallery_image($image_id);
                $notice = 'Image deleted.';
            }
        } catch (Throwable $e) {
            $error = 'Image could not be deleted.';
        }
    }

    if ($action === 'set_primary_image') {
        $image_id = (int) ($_POST['image_id'] ?? 0);

        try {
            if ($image_id > 0) {
                sparrow_set_gallery_primary_image($image_id);
                $notice = 'Primary image updated.';
            }
        } catch (Throwable $e) {
            $error = 'Primary image could not be updated.';
        }
    }
}

if (!empty($_GET['saved'])) {
    $notice = 'Gallery item saved.';
}

if (!empty($_GET['added'])) {
    $notice = 'Gallery item saved. Add the next one below.';
}

if (!empty($_GET['photos_added'])) {
    $notice = 'Photos added.';
}

$item = $item_id > 0 ? sparrow_get_gallery_item($item_id) : [
    'title' => '',
    'category' => 'Shirts',
    'description' => '',
    'featured' => 0,
    'show_public' => 1,
    'status' => 'Published',
    'sort_order' => 0,
];

$images = $item_id > 0 ? sparrow_get_gallery_item_images($item_id) : [];
$categories = sparrow_gallery_categories();

sparrow_backyard_header($item_id > 0 ? 'Edit Gallery Item' : 'Add Gallery Item');

?>

<?php if ($notice): ?>
    <div class="notice-success">
        <?php echo sparrow_escape($notice); ?>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="notice-error">
        <?php echo sparrow_escape($error); ?>
    </div>
<?php endif; ?>

<section class="card">
    <div class="page-heading-row">
        <div>
            <h1><?php echo $item_id > 0 ? 'Edit Gallery Item' : 'Add Gallery Item'; ?></h1>
            <p class="muted">
                Add finished work photos, categories, and public display settings.
            </p>
        </div>

<div class="heading-actions">
    <?php if ($item_id > 0): ?>
        <form method="post" style="display:inline;">
            <input type="hidden" name="action" value="create_marketing_post">
            <button type="submit" class="button">
                Create Marketing Post
            </button>
        </form>

        <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/backyard/gallery-edit.php')); ?>">
            Add Another Gallery Item
        </a>
    <?php endif; ?>

    <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/backyard/gallery.php')); ?>">
        Back to Gallery
    </a>
</div>
    </div>
</section>

<section class="card">
    <h2>Gallery Details</h2>

    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="action" value="save_gallery_item">

        <div class="form-grid">
            <div>
                <label for="title">Title</label>
                <input
                    type="text"
                    id="title"
                    name="title"
                    value="<?php echo sparrow_escape($item['title'] ?? ''); ?>"
                    required
                >
            </div>

            <div>
                <label for="category">Category</label>
                <select id="category" name="category" required>
                    <?php foreach ($categories as $category): ?>
                        <option
                            value="<?php echo sparrow_escape($category); ?>"
                            <?php echo (($item['category'] ?? '') === $category) ? 'selected' : ''; ?>
                        >
                            <?php echo sparrow_escape($category); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <label for="status">Status</label>
                <select id="status" name="status">
                    <?php foreach (['Draft', 'Published', 'Hidden'] as $status): ?>
                        <option
                            value="<?php echo sparrow_escape($status); ?>"
                            <?php echo (($item['status'] ?? 'Published') === $status) ? 'selected' : ''; ?>
                        >
                            <?php echo sparrow_escape($status); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <label for="sort_order">Sort Order</label>
                <input
                    type="number"
                    id="sort_order"
                    name="sort_order"
                    value="<?php echo (int) ($item['sort_order'] ?? 0); ?>"
                >
            </div>
        </div>

        <div class="form-section">
            <label for="description">Description</label>
            <textarea
                id="description"
                name="description"
                rows="5"
            ><?php echo sparrow_escape($item['description'] ?? ''); ?></textarea>
        </div>

        <div class="form-grid">
            <div>
                <label>
                    <input
                        type="checkbox"
                        name="featured"
                        value="1"
                        style="width:auto;"
                        <?php echo !empty($item['featured']) ? 'checked' : ''; ?>
                    >
                    Featured item
                </label>
            </div>

            <div>
                <label>
                    <input
                        type="checkbox"
                        name="show_public"
                        value="1"
                        style="width:auto;"
                        <?php echo !empty($item['show_public']) ? 'checked' : ''; ?>
                    >
                    Show on public website
                </label>
            </div>
        </div>

        <div class="form-section">
            <label for="gallery_images">Upload Photos</label>
            <input
                type="file"
                id="gallery_images"
                name="gallery_images[]"
                accept="image/jpeg,image/png,image/gif,image/webp"
                multiple
            >

            <p class="muted">
                You can upload more than one photo. The first image becomes the main photo unless you choose another one.
            </p>
        </div>

        <div class="form-actions">
    <button type="submit" name="save_mode" value="save_stay" class="button">
        Save Gallery Item
    </button>

    <button type="submit" name="save_mode" value="save_add_another" class="button button-secondary">
        Save & Add Another
    </button>

    <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/backyard/gallery.php')); ?>">
        Cancel
    </a>
</div>
    </form>
</section>

<?php if ($item_id > 0): ?>
    <section class="card">
        <h2>Photos for This Gallery Item</h2>

        <div class="gallery-photo-upload-card">
            <h3>Add More Photos to This Same Item</h3>

            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="action" value="upload_more_images">

                <label for="gallery_images_more">Upload More Photos</label>
                <input
                    type="file"
                    id="gallery_images_more"
                    name="gallery_images[]"
                    accept="image/jpeg,image/png,image/gif,image/webp"
                    multiple
                >

                <div class="form-actions">
                    <button type="submit" class="button">
                        Add Photos
                    </button>
                </div>
            </form>
			<p class="muted">
    Use this only for extra angles or extra photos of this same item. For a different product, create a new gallery item.
</p>
        </div>

        <?php if (!$images): ?>
            <p class="muted">
                No photos uploaded yet.
            </p>
        <?php else: ?>
            <div class="gallery-image-grid">
                <?php foreach ($images as $image): ?>
                    <div class="gallery-image-card">
                        <img
                            src="<?php echo sparrow_escape(sparrow_url($image['image_path'])); ?>"
                            alt="<?php echo sparrow_escape($image['alt_text'] ?: ($item['title'] ?? 'Gallery image')); ?>"
                        >

                        <?php if ((int) $image['is_primary'] === 1): ?>
                            <span class="gallery-pill gallery-pill-green">Primary</span>
                        <?php endif; ?>

                        <form method="post" class="gallery-image-edit-form">
                            <input type="hidden" name="action" value="update_image_details">
                            <input type="hidden" name="image_id" value="<?php echo (int) $image['id']; ?>">

                            <label>
                                Image Alt Text
                                <input
                                    type="text"
                                    name="alt_text"
                                    value="<?php echo sparrow_escape($image['alt_text'] ?? ''); ?>"
                                    placeholder="Example: Faith-based pink shirt with cross design"
                                >
                            </label>

                            <label>
                                Sort Order
                                <input
                                    type="number"
                                    name="sort_order"
                                    value="<?php echo (int) ($image['sort_order'] ?? 0); ?>"
                                >
                            </label>

                            <button type="submit" class="button button-secondary">
                                Save Image Details
                            </button>
                        </form>

                        <form method="post" enctype="multipart/form-data" class="gallery-image-edit-form">
                            <input type="hidden" name="action" value="replace_image">
                            <input type="hidden" name="image_id" value="<?php echo (int) $image['id']; ?>">

                            <label>
                                Replace Photo
                                <input
                                    type="file"
                                    name="replace_image"
                                    accept="image/jpeg,image/png,image/gif,image/webp"
                                >
                            </label>

                            <button type="submit" class="button button-secondary">
                                Replace Photo
                            </button>
                        </form>

                        <div class="form-actions">
                            <?php if ((int) $image['is_primary'] !== 1): ?>
                                <form method="post">
                                    <input type="hidden" name="action" value="set_primary_image">
                                    <input type="hidden" name="image_id" value="<?php echo (int) $image['id']; ?>">
                                    <button type="submit" class="button button-secondary">
                                        Make Primary
                                    </button>
                                </form>
                            <?php endif; ?>

                            <form method="post" onsubmit="return confirm('Delete this image?');">
                                <input type="hidden" name="action" value="delete_image">
                                <input type="hidden" name="image_id" value="<?php echo (int) $image['id']; ?>">
                                <button type="submit" class="button button-secondary">
                                    Delete
                                </button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
<?php endif; ?>

<?php sparrow_backyard_footer(); ?>