<?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';

$user = sparrow_require_backyard_login();

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

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

    try {
        if ($action === 'merge_gallery_items') {
            $selected_ids = $_POST['selected_ids'] ?? [];
            $keep_item_id = (int) ($_POST['keep_item_id'] ?? 0);

            $result = sparrow_merge_gallery_items(
                $selected_ids,
                $keep_item_id
            );

            $notice = sprintf(
                'Merged %d item(s) into "%s". %d image(s) were added.',
                $result['items_merged'],
                $result['keep_title'],
                $result['images_moved']
            );

            if ($result['duplicates_skipped'] > 0) {
                $notice .= sprintf(
                    ' %d duplicate image path(s) were skipped.',
                    $result['duplicates_skipped']
                );
            }
        } elseif ($action === 'bulk_update_gallery_items') {
            $selected_ids = $_POST['selected_ids'] ?? [];
            $category = trim($_POST['bulk_category'] ?? '');
            $status = trim($_POST['bulk_status'] ?? '');

            $show_public_raw = $_POST['bulk_show_public'] ?? '';

            $show_public = $show_public_raw === ''
                ? null
                : (int) $show_public_raw;

            $updated_count = sparrow_bulk_update_gallery_items(
                $selected_ids,
                $category,
                $status,
                $show_public
            );

            $notice = sprintf(
                'Bulk changes applied to %d gallery item(s).',
                $updated_count
            );
        } elseif ($action === 'delete_gallery_item') {
            $item_id = (int) ($_POST['item_id'] ?? 0);

            if ($item_id > 0) {
                sparrow_delete_gallery_item($item_id);
                $notice = 'Gallery item deleted.';
            }
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

$categories = sparrow_gallery_categories();
$items = sparrow_get_gallery_items(true);

sparrow_backyard_header('Gallery');

?>

<?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>Gallery</h1>
            <p class="muted">
                Manage completed work that can show on the public website.
            </p>
        </div>

        <div class="heading-actions">
            <a class="button" href="<?php echo sparrow_escape(sparrow_url('/backyard/gallery-edit.php')); ?>">
                Add Gallery Items
            </a>
			
			<a
    class="button button-secondary"
    href="<?php echo sparrow_escape(sparrow_url('/backyard/gallery-bulk-upload.php')); ?>"
>
    Bulk Upload
</a>

            <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/gallery.php')); ?>" target="_blank">
                View Public Gallery
            </a>
        </div>
    </div>
</section>

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

    <?php if (!$items): ?>
        <p class="muted">
            No gallery items yet. Add your first finished shirt, koozie, or custom project.
        </p>
    <?php else: ?>
<form
    method="post"
    id="gallery-bulk-form"
    class="gallery-bulk-toolbar"
>
    <strong id="gallery-selected-count">
        0 selected
    </strong>

    <button
        type="submit"
        name="action"
        value="merge_gallery_items"
        class="button button-secondary"
        id="gallery-merge-button"
        disabled
    >
        Merge Selected
    </button>

    <div class="gallery-bulk-divider"></div>

    <select name="bulk_category" id="gallery-bulk-category">
        <option value="">Do not change category</option>

        <?php foreach ($categories as $category): ?>
            <option value="<?php echo sparrow_escape($category); ?>">
                <?php echo sparrow_escape($category); ?>
            </option>
        <?php endforeach; ?>
    </select>

    <select name="bulk_status" id="gallery-bulk-status">
        <option value="">Do not change status</option>
        <option value="Draft">Draft</option>
        <option value="Published">Published</option>
        <option value="Hidden">Hidden</option>
    </select>

    <select
        name="bulk_show_public"
        id="gallery-bulk-show-public"
    >
        <option value="">Do not change visibility</option>
        <option value="1">Shown on Website</option>
        <option value="0">Hidden from Website</option>
    </select>

    <button
        type="submit"
        name="action"
        value="bulk_update_gallery_items"
        class="button"
        id="gallery-bulk-edit-button"
        disabled
    >
        Apply Bulk Changes
    </button>
</form>
        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
					<th class="gallery-select-cell">
    <label class="gallery-select-control">
        <input type="checkbox" id="gallery-select-all">
        <span>All</span>
    </label>
</th>
                        <th>Photo</th>
                        <th>Title</th>
                        <th>Category</th>
                        <th>Public</th>
                        <th>Status</th>
                        <th>Featured</th>
                        <th>Photos</th>
                        <th>Actions</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($items as $item): ?>
                        <tr>
						<td class="gallery-select-cell">
    <label class="gallery-select-control">
        <input
            type="checkbox"
            name="selected_ids[]"
            value="<?php echo (int) $item['id']; ?>"
            class="gallery-item-checkbox"
            form="gallery-bulk-form"
        >
        <span>Select</span>
    </label>

    <label class="gallery-select-control gallery-keep-control">
        <input
            type="radio"
            name="keep_item_id"
            value="<?php echo (int) $item['id']; ?>"
            class="gallery-keep-radio"
            form="gallery-bulk-form"
        >
        <span>Keep</span>
    </label>
</td>
                            <td>
                                <?php if (!empty($item['primary_image'])): ?>
                                    <img
                                        class="gallery-admin-thumb"
                                        src="<?php echo sparrow_escape(sparrow_url($item['primary_image'])); ?>"
                                        alt="<?php echo sparrow_escape($item['title']); ?>"
                                    >
                                <?php else: ?>
                                    <span class="gallery-empty-thumb">No photo</span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <strong><?php echo sparrow_escape($item['title']); ?></strong>
                                <?php if (!empty($item['description'])): ?>
                                    <br>
                                    <span class="muted">
                                        <?php echo sparrow_escape(mb_strimwidth($item['description'], 0, 90, '...')); ?>
                                    </span>
                                <?php endif; ?>
                            </td>

                            <td><?php echo sparrow_escape($item['category']); ?></td>

                            <td>
                                <?php if ((int) $item['show_public'] === 1): ?>
                                    <span class="gallery-pill gallery-pill-green">Shown</span>
                                <?php else: ?>
                                    <span class="gallery-pill gallery-pill-muted">Hidden</span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <span class="gallery-pill">
                                    <?php echo sparrow_escape($item['status']); ?>
                                </span>
                            </td>

                            <td>
                                <?php echo ((int) $item['featured'] === 1) ? 'Yes' : 'No'; ?>
                            </td>

                            <td>
                                <?php echo (int) $item['image_count']; ?>
                            </td>

                            <td>
                                <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/backyard/gallery-edit.php?id=' . (int) $item['id'])); ?>">
                                    Edit
                                </a>

                                <form method="post" style="display:inline;" onsubmit="return confirm('Delete this gallery item?');">
                                    <input type="hidden" name="action" value="delete_gallery_item">
                                    <input type="hidden" name="item_id" value="<?php echo (int) $item['id']; ?>">
                                    <button type="submit" class="button button-secondary">
                                        Delete
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const bulkForm = document.getElementById('gallery-bulk-form');
    const selectAll = document.getElementById('gallery-select-all');

    const itemCheckboxes = Array.from(
        document.querySelectorAll('.gallery-item-checkbox')
    );

    const keepRadios = Array.from(
        document.querySelectorAll('.gallery-keep-radio')
    );

    const selectedCount = document.getElementById(
        'gallery-selected-count'
    );

    const mergeButton = document.getElementById(
        'gallery-merge-button'
    );

    const bulkEditButton = document.getElementById(
        'gallery-bulk-edit-button'
    );

    const categorySelect = document.getElementById(
        'gallery-bulk-category'
    );

    const statusSelect = document.getElementById(
        'gallery-bulk-status'
    );

    const visibilitySelect = document.getElementById(
        'gallery-bulk-show-public'
    );

    function getCheckedItems() {
        return itemCheckboxes.filter(function (checkbox) {
            return checkbox.checked;
        });
    }

    function hasBulkChanges() {
        return (
            categorySelect.value !== '' ||
            statusSelect.value !== '' ||
            visibilitySelect.value !== ''
        );
    }

    function updateBulkControls() {
        const checkedItems = getCheckedItems();

        selectedCount.textContent =
            checkedItems.length + ' selected';

        mergeButton.disabled = checkedItems.length < 2;

        bulkEditButton.disabled =
            checkedItems.length < 1 ||
            !hasBulkChanges();

        selectAll.checked =
            itemCheckboxes.length > 0 &&
            checkedItems.length === itemCheckboxes.length;

        selectAll.indeterminate =
            checkedItems.length > 0 &&
            checkedItems.length < itemCheckboxes.length;

        keepRadios.forEach(function (radio) {
            const matchingCheckbox = itemCheckboxes.find(
                function (checkbox) {
                    return checkbox.value === radio.value;
                }
            );

            if (
                matchingCheckbox &&
                !matchingCheckbox.checked &&
                radio.checked
            ) {
                radio.checked = false;
            }
        });
    }

    selectAll.addEventListener('change', function () {
        itemCheckboxes.forEach(function (checkbox) {
            checkbox.checked = selectAll.checked;
        });

        updateBulkControls();
    });

    itemCheckboxes.forEach(function (checkbox) {
        checkbox.addEventListener(
            'change',
            updateBulkControls
        );
    });

    keepRadios.forEach(function (radio) {
        radio.addEventListener('change', function () {
            const matchingCheckbox = itemCheckboxes.find(
                function (checkbox) {
                    return checkbox.value === radio.value;
                }
            );

            if (matchingCheckbox) {
                matchingCheckbox.checked = true;
            }

            updateBulkControls();
        });
    });

    [
        categorySelect,
        statusSelect,
        visibilitySelect
    ].forEach(function (select) {
        select.addEventListener(
            'change',
            updateBulkControls
        );
    });

    bulkForm.addEventListener('submit', function (event) {
        const submittedButton = event.submitter;

        if (!submittedButton) {
            event.preventDefault();
            return;
        }

        const checkedItems = getCheckedItems();

        if (submittedButton.value === 'merge_gallery_items') {
            const keptItem = keepRadios.find(function (radio) {
                return radio.checked;
            });

            if (checkedItems.length < 2) {
                event.preventDefault();
                alert('Select at least two gallery items.');
                return;
            }

            if (!keptItem) {
                event.preventDefault();
                alert(
                    'Mark one selected gallery item as Keep.'
                );
                return;
            }

            if (!confirm(
                'Merge ' +
                checkedItems.length +
                ' gallery items into the item marked Keep?'
            )) {
                event.preventDefault();
            }
        }

        if (
            submittedButton.value ===
            'bulk_update_gallery_items'
        ) {
            if (checkedItems.length < 1) {
                event.preventDefault();
                alert('Select at least one gallery item.');
                return;
            }

            if (!hasBulkChanges()) {
                event.preventDefault();
                alert('Choose at least one bulk change.');
                return;
            }

            if (!confirm(
                'Apply these changes to ' +
                checkedItems.length +
                ' selected gallery item(s)?'
            )) {
                event.preventDefault();
            }
        }
    });

    updateBulkControls();
});
</script>

<?php sparrow_backyard_footer(); ?>