<?php
// includes/photo_manager.php
//
// Fully AJAX, in-place photo upload + gallery. No page navigation, no new
// tab — everything happens inside whichever modal included this file.
// Requires $pdo and $jobPkId to already be set by the including page.
//
// Optional: set $photoManagerTrainingMode = true before including this file
// for Training jobs — this removes the "Type" dropdown entirely and forces
// every upload to be tagged "Trainee Photo", since a training job only
// ever needs the one portrait photo and a dropdown just invites picking
// the wrong type by mistake (exactly what was happening before).

if (!isset($pdo, $jobPkId)) {
    return;
}

$photoManagerTrainingMode = $photoManagerTrainingMode ?? false;
$uniqueId = 'photoMgr' . (int) $jobPkId;
?>
<div class="card mb-3">
    <div class="card-header fw-bold"><?= $photoManagerTrainingMode ? 'Trainee Photo' : 'Inspection Photos'; ?></div>
    <div class="card-body">

        <div id="<?= $uniqueId; ?>-alert"></div>

        <form id="<?= $uniqueId; ?>-form" class="row g-2 align-items-end mb-3">
            <input type="hidden" name="job_id" value="<?= (int) $jobPkId; ?>">
            <?php if ($photoManagerTrainingMode): ?>
                <input type="hidden" name="photo_type" value="Trainee Photo">
                <div class="col-md-7">
                    <label class="form-label small mb-1">Photo (used as the certificate portrait)</label>
                    <input type="file" name="photo" accept="image/jpeg,image/png,image/webp" class="form-control form-control-sm" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label small mb-1">Caption (optional)</label>
                    <input type="text" name="caption" class="form-control form-control-sm" maxlength="255">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-sm btn-primary w-100">Upload</button>
                </div>
            <?php else: ?>
                <div class="col-md-4">
                    <label class="form-label small mb-1">Photo</label>
                    <input type="file" name="photo" accept="image/jpeg,image/png,image/webp" class="form-control form-control-sm" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label small mb-1">Type</label>
                    <select name="photo_type" class="form-select form-select-sm">
                        <option value="Overview">Overview</option>
                        <option value="Nameplate">Nameplate</option>
                        <option value="Defect">Defect</option>
                        <option value="Test">Test in progress</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label small mb-1">Caption (optional)</label>
                    <input type="text" name="caption" class="form-control form-control-sm" maxlength="255">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-sm btn-primary w-100">Upload</button>
                </div>
            <?php endif; ?>
        </form>

        <div id="<?= $uniqueId; ?>-gallery">
            <?php include __DIR__ . '/photo_gallery_fragment.php'; ?>
        </div>
    </div>
</div>

<script>
(function () {
    var jobId = <?= (int) $jobPkId; ?>;
    var form = document.getElementById('<?= $uniqueId; ?>-form');
    var alertBox = document.getElementById('<?= $uniqueId; ?>-alert');
    var galleryBox = document.getElementById('<?= $uniqueId; ?>-gallery');

    function refreshGallery() {
        fetch('includes/photo_gallery_fragment.php?job_id=' + jobId)
            .then(function (r) { return r.text(); })
            .then(function (html) { galleryBox.innerHTML = html; bindDeleteButtons(); });
    }

    function bindDeleteButtons() {
        galleryBox.querySelectorAll('.js-delete-photo').forEach(function (link) {
            link.addEventListener('click', function () {
                if (!confirm('Remove this photo?')) return;
                var photoId = link.getAttribute('data-photo-id');
                fetch('delete_photo.php?photo_id=' + photoId + '&csrf_token=' + encodeURIComponent(document.querySelector('meta[name="csrf-token"]').content))
                    .then(function (r) { return r.json(); })
                    .then(function (data) {
                        if (data.status === 'success') {
                            refreshGallery();
                        } else {
                            alertBox.innerHTML = '<div class="alert alert-danger py-2">' + (data.message || 'Delete failed.') + '</div>';
                        }
                    });
            });
        });
    }

    form.addEventListener('submit', function (e) {
        e.preventDefault();
        var formData = new FormData(form);
        formData.append('csrf_token', document.querySelector('meta[name="csrf-token"]').content);
        var btn = form.querySelector('button[type="submit"]');
        btn.disabled = true;
        alertBox.innerHTML = '<div class="alert alert-info py-2">Uploading...</div>';

        fetch('upload_photo.php', { method: 'POST', body: formData })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (data.status === 'success') {
                    alertBox.innerHTML = '';
                    form.reset();
                    refreshGallery();
                } else {
                    alertBox.innerHTML = '<div class="alert alert-danger py-2">' + (data.message || 'Upload failed.') + '</div>';
                }
            })
            .catch(function (err) {
                alertBox.innerHTML = '<div class="alert alert-danger py-2">Network error: ' + err.message + '</div>';
            })
            .finally(function () { btn.disabled = false; });
    });

    bindDeleteButtons();
})();
</script>
