<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\ResponseInterface;

class Photos extends Controller
{
    public function serve($filename)
    {
        $photoPath = WRITEPATH . 'uploads/photos/' . $filename;
        
        // Check if file exists and is within the photos directory
        if (!file_exists($photoPath) || !is_file($photoPath)) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
        
        // Security check - ensure the file is within the photos directory
        $realPhotoPath = realpath($photoPath);
        $realPhotosDir = realpath(WRITEPATH . 'uploads/photos/');
        
        if (!$realPhotoPath || !$realPhotosDir || strpos($realPhotoPath, $realPhotosDir) !== 0) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
        
        // Get file info
        $mimeType = mime_content_type($photoPath);
        $fileSize = filesize($photoPath);
        
        // Set appropriate headers
        $this->response->setHeader('Content-Type', $mimeType);
        $this->response->setHeader('Content-Length', (string) $fileSize);
        $this->response->setHeader('Cache-Control', 'public, max-age=3600');
        
        // Output the file
        readfile($photoPath);
        
        return $this->response;
    }
}