<?php
class TripAttachmentsController extends Controller
{
    public function uploadAction($trip_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Trips/view/' . (int)$trip_id); return; }

        $tripId = (int)$trip_id;
        $rs = (new DB())->mySelect("SELECT c0d FROM trips WHERE c0d = :id AND deleted = 0 LIMIT 1", [':id' => $tripId]);
        if (empty($rs)) { $this->notFound('Trip'); return; }

        if (empty($_FILES['photo']['name']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
            $_SESSION['flash_tenant_msg']  = 'Please choose a photo to upload.';
            $_SESSION['flash_tenant_type'] = 'danger';
            Router::redirect('Trips/view/' . $tripId); return;
        }

        $up = $this->savePhoto($_FILES['photo'], $tripId);
        if (!$up['ok']) {
            $_SESSION['flash_tenant_msg']  = $up['msg'];
            $_SESSION['flash_tenant_type'] = 'danger';
            Router::redirect('Trips/view/' . $tripId); return;
        }

        (new TripAttachments())->create([
            'trip_id'      => $tripId,
            'trip_stop_id' => (int)($_POST['trip_stop_id'] ?? 0) ?: null,
            'category'     => $_POST['category'] ?? 'other',
            'caption'      => $_POST['caption']  ?? '',
            'file_url'     => $up['url'],
            'file_name'    => $up['orig_name'],
            'file_size'    => $up['size'],
            'mime_type'    => $up['mime'],
            'source'       => 'web',
            'uploaded_by'  => $this->currentUserId(),
        ]);

        $_SESSION['flash_tenant_msg']  = 'Photo added.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('Trips/view/' . $tripId);
    }

    public function deleteAction($attach_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Trips'); return; }

        $m = new TripAttachments();
        $a = $m->byId((int)$attach_id);
        if (!$a) { $this->notFound('Attachment'); return; }

        $m->softDelete((int)$attach_id, $this->currentUserId());
        $_SESSION['flash_tenant_msg']  = 'Photo removed.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('Trips/view/' . (int)$a['trip_id']);
    }

    private function notFound(string $what): void
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('generals/fb_page', [
            'page_title' => 'Not found',
            'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($what) . ' not found.</div>',
        ]);
    }

    /**
     * Save an uploaded photo under uploads/trip/{trip_id}/. Whitelist by
     * extension AND MIME. Returns {ok, url, orig_name, size, mime} or
     * {ok:false, msg}.
     */
    private function savePhoto(array $file, int $tripId): array
    {
        $maxBytes = defined('MAX_UPLOAD_SIZE') ? MAX_UPLOAD_SIZE : (8 * 1024 * 1024);
        if ($file['size'] > $maxBytes) return ['ok' => false, 'msg' => 'File exceeds max size.'];

        $allowedExt  = ['jpg','jpeg','png','webp','heic'];
        $allowedMime = ['image/jpeg','image/png','image/webp','image/heic','image/heif'];

        $origName = basename((string)$file['name']);
        $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExt, true)) return ['ok' => false, 'msg' => "Type .{$ext} not allowed."];

        $mime = '';
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        if ($finfo) { $mime = finfo_file($finfo, $file['tmp_name']) ?: ''; finfo_close($finfo); }
        if ($mime && !in_array($mime, $allowedMime, true)) return ['ok' => false, 'msg' => 'File content does not match an image type.'];

        $destDir = UPLOAD_PATH . 'trip' . DS . (int)$tripId;
        if (!is_dir($destDir)) @mkdir($destDir, 0775, true);
        $name = date('Ymd_His') . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
        $path = $destDir . DS . $name;
        if (!move_uploaded_file($file['tmp_name'], $path)) return ['ok' => false, 'msg' => 'Server could not save the photo.'];

        return [
            'ok'        => true,
            'url'       => UPLOAD_URL . 'trip/' . (int)$tripId . '/' . $name,
            'orig_name' => $origName,
            'size'      => (int)$file['size'],
            'mime'      => $mime ?: 'image/' . $ext,
        ];
    }
}
