{{-- Before/after clinical photography for a patient (shared ClinicCore feature). --}}
<style>
  .ph-toolbar { display:flex; flex-wrap:wrap; gap:8px; align-items:center; margin-bottom:14px; }
  .ph-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(150px,1fr)); gap:12px; }
  .ph-group-title { font-size:12px; font-weight:700; color:#475569; text-transform:uppercase; letter-spacing:.4px; margin:16px 0 8px; border-bottom:1px solid #eef2f7; padding-bottom:4px; }
  .ph-card { position:relative; border:1px solid #e2e8f0; border-radius:10px; overflow:hidden; background:#fff; cursor:pointer; transition:box-shadow .15s, border-color .15s; }
  .ph-card:hover { box-shadow:0 4px 14px rgba(15,23,42,.12); }
  .ph-card.sel { border-color:#0ea5e9; box-shadow:0 0 0 3px rgba(14,165,233,.25); }
  .ph-img { width:100%; height:130px; object-fit:cover; display:block; background:#f1f5f9; }
  .ph-meta { padding:6px 8px; font-size:11px; color:#334155; }
  .ph-badge { position:absolute; top:6px; left:6px; font-size:10px; font-weight:700; padding:2px 7px; border-radius:20px; color:#fff; text-transform:uppercase; letter-spacing:.3px; }
  .ph-badge.before{background:#f59e0b;} .ph-badge.after{background:#22c55e;} .ph-badge.baseline{background:#6366f1;} .ph-badge.progress{background:#0ea5e9;} .ph-badge.other{background:#94a3b8;}
  .ph-del { position:absolute; top:6px; right:6px; background:rgba(15,23,42,.55); color:#fff; border:none; width:22px; height:22px; border-radius:50%; font-size:11px; cursor:pointer; display:none; }
  .ph-card:hover .ph-del { display:block; }
  .ph-empty { text-align:center; color:#94a3b8; padding:36px 0; }
  .ph-cmp { display:flex; gap:12px; }
  .ph-cmp > div { flex:1; text-align:center; }
  .ph-cmp img { width:100%; border-radius:8px; }
</style>

<div class="ph-toolbar">
    @can('clinic.manage_pets')
    <button type="button" class="btn btn-primary btn-sm" id="ph_open_upload">
        <i class="fa fa-camera"></i> Upload Photos
    </button>
    @endcan
    <button type="button" class="btn btn-default btn-sm" id="ph_compare_toggle">
        <i class="fa fa-columns"></i> Compare Before / After
    </button>
    <span id="ph_compare_hint" class="text-muted" style="font-size:12px;display:none;">Select two photos to compare…</span>
</div>

<div id="ph_gallery"><div class="ph-empty"><i class="fa fa-spinner fa-spin"></i> Loading…</div></div>

{{-- Upload modal --}}
<div class="modal fade" id="ph_upload_modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <form id="ph_upload_form" enctype="multipart/form-data">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title"><i class="fa fa-camera"></i> Upload Clinical Photos</h4>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>Photos <span class="text-danger">*</span></label>
            <input type="file" name="photos[]" accept="image/*" multiple required class="form-control">
            <small class="text-muted">JPG / PNG / WEBP, up to 12 MB each. Multiple allowed.</small>
          </div>
          <div class="row">
            <div class="col-xs-6 form-group">
              <label>Phase</label>
              <select name="phase" class="form-control">
                <option value="before">Before</option>
                <option value="after">After</option>
                <option value="baseline">Baseline</option>
                <option value="progress" selected>Progress</option>
                <option value="other">Other</option>
              </select>
            </div>
            <div class="col-xs-6 form-group">
              <label>Date taken</label>
              <input type="date" name="taken_at" class="form-control" value="{{ now()->toDateString() }}">
            </div>
          </div>
          <div class="form-group">
            <label>Body area</label>
            <input type="text" name="body_area" class="form-control" list="ph_area_list" placeholder="e.g. Face, Left cheek, Scalp, Back">
            <datalist id="ph_area_list">
              <option>Face</option><option>Forehead</option><option>Cheeks</option><option>Nose</option>
              <option>Chin</option><option>Neck</option><option>Scalp</option><option>Chest</option>
              <option>Back</option><option>Arms</option><option>Hands</option><option>Legs</option><option>Full body</option>
            </datalist>
          </div>
          <div class="form-group">
            <label>Caption / note</label>
            <input type="text" name="caption" class="form-control" maxlength="255" placeholder="Optional">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary" id="ph_upload_submit"><i class="fa fa-upload"></i> Upload</button>
        </div>
      </form>
    </div>
  </div>
</div>

{{-- Compare / lightbox modal --}}
<div class="modal fade" id="ph_view_modal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title" id="ph_view_title">Photo</h4>
      </div>
      <div class="modal-body" id="ph_view_body" style="text-align:center;"></div>
    </div>
  </div>
</div>

<script>
(function phInit(){
    if (typeof window.jQuery === 'undefined') { return setTimeout(phInit, 60); }
    jQuery(function ($) {
        var listUrl   = '{{ route('clinic.patients.photos.index', $patient->id) }}';
        var storeUrl  = '{{ route('clinic.patients.photos.store', $patient->id) }}';
        var delBase   = '{{ url('clinic/photos') }}';
        var token     = '{{ csrf_token() }}';
        var phases    = {!! json_encode(\Modules\ClinicCore\Entities\ClcClinicalPhoto::phases()) !!};
        var compareMode = false, selected = [];

        function esc(s){ return $('<i>').text(s == null ? '' : s).html(); }

        function render(photos){
            var $g = $('#ph_gallery'); $g.empty();
            var badge = $('#photos_count_badge');
            if (photos.length) { badge.text(photos.length).show(); } else { badge.hide(); }
            if (!photos.length){ $g.html('<div class="ph-empty"><i class="fa fa-camera fa-2x" style="opacity:.3"></i><p style="margin-top:8px;">No clinical photos yet.</p></div>'); return; }
            // group by body area
            var groups = {};
            photos.forEach(function(p){ var k = p.body_area || 'Unspecified area'; (groups[k] = groups[k] || []).push(p); });
            Object.keys(groups).sort().forEach(function(area){
                $g.append('<div class="ph-group-title"><i class="fa fa-map-marker-alt"></i> '+esc(area)+'</div>');
                var $grid = $('<div class="ph-grid"></div>');
                groups[area].forEach(function(p){
                    var card = $(
                        '<div class="ph-card" data-id="'+p.id+'">'+
                          '<span class="ph-badge '+esc(p.phase)+'">'+esc(phases[p.phase]||p.phase)+'</span>'+
                          '<button class="ph-del" title="Delete">&times;</button>'+
                          '<img class="ph-img" src="'+esc(p.url)+'" loading="lazy">'+
                          '<div class="ph-meta"><strong>'+esc(p.taken_at||'')+'</strong>'+(p.caption?'<br>'+esc(p.caption):'')+'</div>'+
                        '</div>');
                    card.data('photo', p);
                    $grid.append(card);
                });
                $g.append($grid);
            });
        }

        function load(){
            $.getJSON(listUrl).done(function(res){ render(res.photos || []); })
             .fail(function(){ $('#ph_gallery').html('<div class="ph-empty text-danger">Could not load photos.</div>'); });
        }

        // lazy-load when the Photos tab is first shown
        var loaded = false;
        $('a[href="#tab-photos"]').on('shown.bs.tab', function(){ if(!loaded){ loaded = true; load(); } });
        // if the tab is already active on page load
        if ($('#tab-photos').hasClass('active')) { loaded = true; load(); }

        // Upload
        $('#ph_open_upload').on('click', function(){ $('#ph_upload_modal').modal('show'); });
        $('#ph_upload_form').on('submit', function(e){
            e.preventDefault();
            var fd = new FormData(this); fd.append('_token', token);
            var $btn = $('#ph_upload_submit').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Uploading…');
            $.ajax({ url: storeUrl, method:'POST', data:fd, processData:false, contentType:false })
             .done(function(res){ $('#ph_upload_modal').modal('hide'); $('#ph_upload_form')[0].reset(); if(window.toastr) toastr.success(res.msg||'Uploaded'); loaded=true; load(); })
             .fail(function(x){ if(window.toastr) toastr.error((x.responseJSON && x.responseJSON.message) || 'Upload failed'); })
             .always(function(){ $btn.prop('disabled', false).html('<i class="fa fa-upload"></i> Upload'); });
        });

        // Delete
        $('#ph_gallery').on('click', '.ph-del', function(e){
            e.stopPropagation();
            var $card = $(this).closest('.ph-card'); var id = $card.data('id');
            if (!confirm('Delete this photo?')) return;
            $.ajax({ url: delBase+'/'+id, method:'DELETE', data:{ _token: token } })
             .done(function(){ if(window.toastr) toastr.success('Deleted'); $card.remove(); var n=$('#ph_gallery .ph-card').length; var b=$('#photos_count_badge'); n?b.text(n).show():b.hide(); })
             .fail(function(){ if(window.toastr) toastr.error('Delete failed'); });
        });

        // Compare toggle
        $('#ph_compare_toggle').on('click', function(){
            compareMode = !compareMode; selected = [];
            $('.ph-card').removeClass('sel');
            $(this).toggleClass('btn-primary btn-default');
            $('#ph_compare_hint').toggle(compareMode);
        });

        // Card click: select (compare) or lightbox
        $('#ph_gallery').on('click', '.ph-card', function(){
            var p = $(this).data('photo');
            if (compareMode){
                var $c = $(this);
                if ($c.hasClass('sel')){ $c.removeClass('sel'); selected = selected.filter(function(x){return x.id!==p.id;}); return; }
                $c.addClass('sel'); selected.push(p);
                if (selected.length === 2){
                    var a = selected[0], b = selected[1];
                    $('#ph_view_title').text('Before / After comparison');
                    $('#ph_view_body').html(
                          '<div class="ph-cmp">'+
                          '<div><span class="ph-badge '+esc(a.phase)+'" style="position:static;display:inline-block;margin-bottom:6px;">'+esc(phases[a.phase]||a.phase)+' · '+esc(a.taken_at||'')+'</span><img src="'+esc(a.url)+'"></div>'+
                          '<div><span class="ph-badge '+esc(b.phase)+'" style="position:static;display:inline-block;margin-bottom:6px;">'+esc(phases[b.phase]||b.phase)+' · '+esc(b.taken_at||'')+'</span><img src="'+esc(b.url)+'"></div>'+
                       '</div>');
                    $('#ph_view_modal').modal('show');
                    selected = []; $('.ph-card').removeClass('sel');
                }
            } else {
                $('#ph_view_title').text((phases[p.phase]||p.phase)+' · '+(p.body_area||'')+' · '+(p.taken_at||''));
                $('#ph_view_body').html('<img src="'+esc(p.url)+'" style="max-width:100%;border-radius:8px;">'+(p.caption?'<p style="margin-top:10px;color:#475569;">'+esc(p.caption)+'</p>':''));
                $('#ph_view_modal').modal('show');
            }
        });
    });
})();
</script>
