<?php
// includes/photo_gallery_fragment.php
// Outputs ONLY the photo grid markup for a given job. Called directly via
// fetch() after every upload/delete to refresh just the gallery, in place,
// with zero page/modal navigation.

if (!isset($pdo)) {
    require __DIR__ . '/../db.php';
}
// SECURITY FIX: this fragment is fetched directly via AJAX - see
// photo_manager.php's refreshGallery, which bypasses whatever
// require_role gate the parent job-edit page already enforced. Without
// an equivalent check here, anyone unauthenticated who requested this
// file directly could enumerate every job's inspection photo paths by
// job_id alone. ajax=true returns a clean 401 instead of an HTML
// redirect, so a logged-out request never dumps a login page's HTML
// into the gallery.
if (!function_exists('current_user')) { require_once __DIR__ . '/auth.php'; }
require_login(true);

$jobPkId = isset($_GET['job_id']) ? (int) $_GET['job_id'] : (isset($jobPkId) ? (int) $jobPkId : 0);

$stmtGallery = $pdo->prepare(
    "SELECT PhotoID, Photo_Path, Photo_Type, Caption
     FROM tbl_inspection_photos
     WHERE JobID = ?
     ORDER BY PhotoID DESC"
);
$stmtGallery->execute([$jobPkId]);
$galleryPhotos = $stmtGallery->fetchAll(PDO::FETCH_ASSOC);
?>
<?php if (empty($galleryPhotos)): ?>
    <p class="text-muted small mb-0">No photos uploaded yet.</p>
<?php else: ?>
    <div class="d-flex flex-wrap gap-2">
        <?php foreach ($galleryPhotos as $p): ?>
            <div style="width:130px;" class="border rounded p-1">
                <img src="<?= htmlspecialchars($p['Photo_Path']); ?>"
                     style="width:100%; height:90px; object-fit:cover;" class="rounded mb-1">
                <div class="small fw-bold text-truncate"><?= htmlspecialchars($p['Photo_Type']); ?></div>
                <a href="javascript:void(0);"
                   class="small text-danger js-delete-photo"
                   data-photo-id="<?= (int) $p['PhotoID']; ?>">Remove</a>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>
