<?php
if (!function_exists('photo_url')) {
    function photo_url($v){
        $v = (string)$v;
        $v = str_replace('\\','/',$v);
        if (preg_match('~^https?://~i',$v)) return $v;
        $v = ltrim($v, '/');
        if ($v === '' || $v === '.' || $v === '..') {
            $path = 'uploads/photos/default.png';
        } elseif (strpos($v, 'uploads/') === 0) {
            $path = $v;
        } elseif (strpos($v, 'photos/') === 0) {
            $path = 'uploads/' . $v;
        } elseif (preg_match('~^[A-Za-z0-9._-]+$~', basename($v))) {
            $path = 'uploads/photos/' . basename($v);
        } else {
            $path = 'uploads/' . ltrim($v,'/');
        }
        $path = preg_replace('~[^A-Za-z0-9/_\.-]~','', $path);
        return base_url($path);
    }
}
?>
<section style="max-width:1400px; margin:20px auto; padding:0 16px">
  <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">
    <div>
      <h1 style="margin:0; font-size:1.6rem;">Gestión de Fotos</h1>
      <p style="margin:4px 0 0; color:#64748b;">Administra y modera las fotos</p>
    </div>
    <a href="<?php echo base_url('/admin'); ?>" style="padding:8px 12px; border:1px solid #e2e8f0; border-radius:8px; background:#f8fafc; text-decoration:none; color:#111827;">← Dashboard</a>
  </div>

  <!-- Filtros -->
  <div style="background:#fff; border:1px solid #e5e7eb; border-radius:12px; padding:16px; margin-bottom:16px;">
    <form method="get" action="<?php echo base_url('/admin/photos'); ?>" style="display:grid; grid-template-columns: 1fr 200px 200px auto; gap:12px; align-items:end;">
      <div>
        <label style="display:block; font-size:.8rem; color:#374151; margin-bottom:4px;">Buscar</label>
        <input type="text" name="q" value="<?php echo htmlspecialchars($_GET['q'] ?? ''); ?>" placeholder="nick, email, texto..." style="width:100%; padding:8px 10px; border:1px solid #d1d5db; border-radius:6px;">
      </div>
      <div>
        <label style="display:block; font-size:.8rem; color:#374151; margin-bottom:4px;">Estado</label>
        <?php $sf = $_GET['status'] ?? ''; ?>
        <select name="status" style="width:100%; padding:8px 10px; border:1px solid #d1d5db; border-radius:6px;">
          <option value="">Todos</option>
          <option value="active"  <?php echo $sf==='active'  ? 'selected':''; ?>>Activas</option>
          <option value="hidden"  <?php echo $sf==='hidden'  ? 'selected':''; ?>>Ocultas</option>
          <option value="deleted" <?php echo $sf==='deleted' ? 'selected':''; ?>>Eliminadas</option>
        </select>
      </div>
      <div>
        <label style="display:block; font-size:.8rem; color:#374151; margin-bottom:4px;">Reportes</label>
        <?php $rf = $_GET['reports'] ?? ''; ?>
        <select name="reports" style="width:100%; padding:8px 10px; border:1px solid #d1d5db; border-radius:6px;">
          <option value="">Todos</option>
          <option value="with_reports" <?php echo $rf==='with_reports' ? 'selected':''; ?>>Con reportes</option>
          <option value="no_reports"   <?php echo $rf==='no_reports'   ? 'selected':''; ?>>Sin reportes</option>
        </select>
      </div>
      <div style="display:flex; gap:8px;">
        <button type="submit" style="padding:8px 14px; border-radius:6px; border:1px solid #d1d5db; background:#fff;">🔍 Filtrar</button>
        <a href="<?php echo base_url('/admin/photos'); ?>" style="padding:8px 14px; border-radius:6px; border:1px solid #d1d5db; background:#f8fafc; text-decoration:none; color:#111827;">🔄 Limpiar</a>
      </div>
    </form>
  </div>

  <?php if (!empty($_SESSION['flash'])): ?>
    <div style="padding: 10px 12px; background:#DBEAFE; border:1px solid #BFDBFE; border-radius:8px; color:#1E3A8A; margin-bottom:16px;">
      <?php echo htmlspecialchars($_SESSION['flash']); unset($_SESSION['flash']); ?>
    </div>
  <?php endif; ?>

  <!-- Tabla de fotos -->
  <div style="background:#fff; border:1px solid #e5e7eb; border-radius:12px; overflow:hidden;">
    <table style="width:100%; border-collapse:collapse; min-width:1000px;">
      <thead style="background:#F8FAFC;">
        <tr>
          <th style="text-align:left; padding:12px;">Foto</th>
          <th style="text-align:left; padding:12px;">Usuario</th>
          <th style="text-align:left; padding:12px;">Descripción</th>
          <th style="text-align:left; padding:12px;">Estado</th>
          <th style="text-align:left; padding:12px;">Fecha</th>
          <th style="text-align:left; padding:12px;">Reportes</th>
          <th style="text-align:left; padding:12px;">Acciones</th>
        </tr>
      </thead>
      <tbody>
      <?php if (!empty($photos)): foreach ($photos as $photo): ?>
        <tr style="border-top:1px solid #F1F5F9;">
          <!-- Columna Foto -->
          <td style="padding:12px; width:90px;">
            <div style="width:80px; height:80px; background:#F3F4F6; border:1px solid #E5E7EB; border-radius:6px; overflow:hidden; display:flex; align-items:center; justify-content:center;">
              <img src="<?php echo photo_url($photo['storage_rel_path'] ?? ''); ?>" alt="" style="width:100%; height:100%; object-fit:cover;">
            </div>
          </td>
          
          <!-- Columna Usuario -->
          <td style="padding:12px; min-width:200px;">
            <div style="font-weight:600;"><?php echo htmlspecialchars($photo['nick'] ?? ''); ?></div>
            <div style="color:#64748b;"><?php echo htmlspecialchars($photo['email'] ?? ''); ?></div>
            <a href="<?php echo base_url('/admin/users/profile?id='.(int)($photo['owner_id'] ?? 0)); ?>" style="font-size:.85rem; color:#3B82F6; text-decoration:none;">Ver perfil</a>
          </td>
          
          <!-- Columna Descripción -->
          <td style="padding:12px; min-width:220px;">
            <?php echo $photo['caption'] ? htmlspecialchars($photo['caption']) : '<span style="color:#94A3B8">Sin descripción</span>'; ?>
          </td>
          
          <!-- Columna Estado -->
          <td style="padding:12px;">
            <?php $st = $photo['status'] ?? ''; ?>
            <?php if ($st): ?>
              <span style="display:inline-flex; align-items:center; gap:6px; padding:4px 8px; border:1px solid #E5E7EB; border-radius:9999px; font-size:.85rem; margin-bottom:6px;">
                <span style="width:8px; height:8px; border-radius:9999px; background:<?php echo $st==='active'?'#10B981':($st==='hidden'?'#F59E0B':'#EF4444'); ?>;"></span>
                <?php echo htmlspecialchars($st); ?>
              </span>
            <?php endif; ?>
            
            <form method="post" action="<?php echo base_url('/admin/photos/set-status'); ?>" style="margin-top:6px; display:flex; gap:6px; align-items:center;">
              <input type="hidden" name="id" value="<?php echo (int)$photo['id']; ?>">
              <select name="status" style="padding:6px 8px; border:1px solid #E5E7EB; border-radius:6px; font-size:.85rem; width:100px;">
                <option value="active"  <?= $st==='active'?'selected':''; ?>>Activo</option>
                <option value="hidden"  <?= $st==='hidden'?'selected':''; ?>>Oculto</option>
                <option value="deleted" <?= $st==='deleted'?'selected':''; ?>>Eliminado</option>
              </select>
              <button type="submit" style="padding:6px 10px; background:#111827; color:#fff; border:none; border-radius:6px; font-size:.85rem;">Guardar</button>
            </form>
              <a href="<?php echo base_url('/photo?id=' . (int)$photo['id']); ?>" target="_blank" rel="noopener noreferrer" style="display:inline-block; margin-top:6px; font-size:.8rem; text-decoration:none; color:#2563EB;">Ver foto</a>
          </td>
          
          <!-- Columna Fecha -->
          <td style="padding:12px; white-space:nowrap;">
            <?php echo htmlspecialchars(date('d/m/Y H:i', strtotime($photo['created_at'] ?? 'now'))); ?>
          </td>
          
          <!-- Columna Reportes -->
          <td style="padding:12px;">
            <?php $pr = (int)($photo['pending_reports'] ?? 0); ?>
            <?php if ($pr > 0): ?>
              <div style="display:flex; align-items:center; gap:4px; margin-bottom:4px;">
                <span style="color:#DC2626;">⚠️ <?php echo $pr; ?></span>
              </div>
              <a href="<?php echo base_url('/admin/reports?q='.urlencode($photo['id'])); ?>" style="font-size:.85rem; color:#3B82F6; text-decoration:none;">Ver reportes</a>
            <?php else: ?>
              <span style="color:#94A3B8;">—</span>
            <?php endif; ?>
          </td>
          
          <!-- Columna Acciones -->
          <td style="padding:12px; min-width:320px;">
            <div style="display:flex; flex-direction:column; gap:8px;">
              
              <!-- Acciones básicas -->
              <div style="display:flex; gap:6px; flex-wrap:wrap;">
                <a href="<?php echo base_url('/photo/'.(int)$photo['id']); ?>" 
                   style="padding:6px 10px; background:#E5E7EB; color:#111827; border-radius:6px; text-decoration:none; font-size:.85rem; display:inline-flex; align-items:center; gap:4px;">
                  👁️ Ver
                </a>
                
                <form method="post" action="<?php echo base_url('/admin/photos/delete'); ?>" style="display:inline;">
                  <input type="hidden" name="id" value="<?php echo (int)$photo['id']; ?>">
                  <button type="submit" onclick="return confirm('¿Eliminar permanentemente esta foto?')" 
                          style="padding:6px 10px; background:#EF4444; color:#fff; border:none; border-radius:6px; font-size:.85rem; display:inline-flex; align-items:center; gap:4px;">
                    🗑️ Eliminar
                  </button>
                </form>
              </div>
              
              <!-- Cambio rápido de estado -->
              <div style="display:flex; gap:6px; flex-wrap:wrap;">
                <form method="post" action="<?php echo base_url('/admin/photos/set-status'); ?>" style="display:flex; gap:4px; align-items:center;">
                  <input type="hidden" name="id" value="<?php echo (int)$photo['id']; ?>">
                  <input type="hidden" name="status" value="hidden">
                  <input type="text" name="reason" placeholder="Motivo" 
                         style="padding:4px 6px; border:1px solid #E5E7EB; border-radius:4px; font-size:.8rem; width:80px;">
                  <button type="submit" 
                          style="padding:4px 8px; background:#F97316; color:#fff; border:none; border-radius:4px; font-size:.8rem; display:inline-flex; align-items:center; gap:2px;">
                    👁️ Ocultar
                  </button>
                </form>
                
                <form method="post" action="<?php echo base_url('/admin/photos/set-status'); ?>" style="display:inline;">
                  <input type="hidden" name="id" value="<?php echo (int)$photo['id']; ?>">
                  <input type="hidden" name="status" value="active">
                  <button type="submit" 
                          style="padding:4px 8px; background:#10B981; color:#fff; border:none; border-radius:4px; font-size:.8rem; display:inline-flex; align-items:center; gap:2px;">
                    ✅ Activar
                  </button>
                </form>
              </div>
              
              <!-- Eliminación lógica -->
              <form method="post" action="<?php echo base_url('/admin/photos/set-status'); ?>" style="display:flex; gap:4px; align-items:center;">
                <input type="hidden" name="id" value="<?php echo (int)$photo['id']; ?>">
                <input type="hidden" name="status" value="deleted">
                <input type="text" name="reason" placeholder="Motivo eliminación" 
                       style="padding:4px 6px; border:1px solid #E5E7EB; border-radius:4px; font-size:.8rem; flex:1;">
                <button type="submit" onclick="return confirm('¿Eliminar lógicamente esta foto?')" 
                        style="padding:4px 8px; background:#EF4444; color:#fff; border:none; border-radius:4px; font-size:.8rem; display:inline-flex; align-items:center; gap:2px;">
                  🗑️ Eliminar
                </button>
              </form>
              
            </div>
          </td>
        </tr>
      <?php endforeach; else: ?>
        <tr>
          <td colspan="7" style="padding:40px; text-align:center; color:#64748b;">
            No hay fotos que coincidan con los filtros seleccionados
          </td>
        </tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- Paginación -->
  <?php if (!empty($photos) && isset($total_pages) && $total_pages > 1): ?>
    <div style="display:flex; justify-content:center; align-items:center; gap:12px; margin-top:20px;">
      <?php if ($current_page > 1): ?>
        <a href="<?php echo base_url('/admin/photos?' . http_build_query(array_merge($_GET, ['page' => $current_page - 1]))); ?>" 
           style="padding:8px 12px; border:1px solid #D1D5DB; border-radius:6px; text-decoration:none; color:#374151;">
          ← Anterior
        </a>
      <?php endif; ?>
      
      <span style="color:#64748B; font-size:.875rem;">
        Página <?php echo $current_page; ?> de <?php echo $total_pages; ?>
      </span>
      
      <?php if ($current_page < $total_pages): ?>
        <a href="<?php echo base_url('/admin/photos?' . http_build_query(array_merge($_GET, ['page' => $current_page + 1]))); ?>" 
           style="padding:8px 12px; border:1px solid #D1D5DB; border-radius:6px; text-decoration:none; color:#374151;">
          Siguiente →
        </a>
      <?php endif; ?>
    </div>
  <?php endif; ?>
</section>