<?php
declare(strict_types=1);

/**
 * /functional/albums/delete.php
 * Видалення фотоальбому разом із фотографіями та папкою альбому.
 *
 * POST:
 * - csrf
 * - album_id
 * - back (optional)
 */

require_once __DIR__ . '/../../includes/start.php';
require_once __DIR__ . '/_lib.php';

if (!headers_sent()) {
    header('X-Robots-Tag: noindex, nofollow, noarchive, nosnippet', true);
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0', true);
    header('Pragma: no-cache', true);
}

if (!function_exists('alb_delete_redirect')) {
    function alb_delete_redirect(string $url, int $code = 302): void
    {
        header('Location: ' . $url, true, $code);
        exit;
    }
}

if (!function_exists('alb_delete_require_login')) {
    function alb_delete_require_login(): void
    {
        if (function_exists('require_login')) {
            require_login();
            return;
        }

        $me = alb_me();
        if (!$me || (int)($me['id'] ?? 0) <= 0) {
            alb_delete_redirect('/login.php');
        }
    }
}

if (!function_exists('alb_delete_safe_back_url')) {
    function alb_delete_safe_back_url(string $back, string $fallback): string
    {
        $back = trim($back);
        if ($back === '') {
            return $fallback;
        }

        if (str_contains($back, "\r") || str_contains($back, "\n")) {
            return $fallback;
        }

        if (!str_starts_with($back, '/')) {
            return $fallback;
        }

        return $back;
    }
}

if (!function_exists('alb_delete_append_query')) {
    function alb_delete_append_query(string $url, array $params): string
    {
        $fragment = '';
        if (str_contains($url, '#')) {
            [$url, $fragment] = explode('#', $url, 2);
            $fragment = '#' . $fragment;
        }

        $path = $url;
        $query = '';

        if (str_contains($url, '?')) {
            [$path, $query] = explode('?', $url, 2);
        }

        $current = [];
        if ($query !== '') {
            parse_str($query, $current);
            if (!is_array($current)) {
                $current = [];
            }
        }

        foreach ($params as $k => $v) {
            $current[(string)$k] = $v;
        }

        $qs = http_build_query($current);
        return $path . ($qs !== '' ? ('?' . $qs) : '') . $fragment;
    }
}

alb_delete_require_login();

$pdo = alb_db();
$me  = alb_me();

if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    alb_delete_redirect('/profile/index.php?tab=albums');
}

$albumId = (int)($_POST['album_id'] ?? 0);
if ($albumId <= 0) {
    alb_delete_redirect('/profile/index.php?tab=albums');
}

$album = alb_album_get($pdo, $albumId);
if (!$album) {
    alb_delete_redirect('/profile/index.php?tab=albums');
}

$owner = alb_user_get($pdo, (int)($album['user_id'] ?? 0));
$fallbackBack = $owner ? alb_profile_albums_url($owner) : '/profile/index.php?tab=albums';

$rawBack = (string)($_POST['back'] ?? '');
$back = alb_delete_safe_back_url($rawBack, $fallbackBack);

if (!alb_csrf_check((string)($_POST['csrf'] ?? ''))) {
    alb_delete_redirect(alb_delete_append_query($back, ['am' => 'csrf']));
}

if (!alb_can_manage_album($album, $me)) {
    alb_delete_redirect(alb_delete_append_query($back, ['am' => 'denied']));
}

$ownerUsername = trim((string)($owner['username'] ?? ''));
if ($ownerUsername === '') {
    $ownerUsername = 'user_' . (int)($album['user_id'] ?? 0);
}

$albumDir = alb_album_dir_abs($ownerUsername, $albumId);
$photos = alb_list_album_photos($pdo, $albumId, 5000, 0);

$ownTx = !$pdo->inTransaction();

try {
    if ($ownTx) {
        $pdo->beginTransaction();
    }

    if ($photos) {
        foreach ($photos as $photo) {
            $photoId = (int)($photo['id'] ?? 0);
            if ($photoId <= 0) {
                continue;
            }

            $st = $pdo->prepare("DELETE FROM album_photos WHERE id = ? LIMIT 1");
            $st->execute([$photoId]);
        }
    }

    $st = $pdo->prepare("UPDATE photo_albums SET cover_photo_id = NULL WHERE id = ? LIMIT 1");
    $st->execute([$albumId]);

    $st = $pdo->prepare("DELETE FROM photo_albums WHERE id = ? LIMIT 1");
    $st->execute([$albumId]);

    if ($ownTx) {
        $pdo->commit();
    }
} catch (Throwable $e) {
    if ($ownTx && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    alb_delete_redirect(alb_delete_append_query($back, ['am' => 'db']));
}

/* після успішного видалення чистимо файли */
foreach ($photos as $photo) {
    $path = trim((string)($photo['file_path'] ?? ''));
    if ($path === '' || str_contains($path, '..')) {
        continue;
    }

    $pathNoQuery = strtok($path, '?');
    if ($pathNoQuery === false) {
        $pathNoQuery = $path;
    }

    $relative = ltrim((string)$pathNoQuery, '/');

    if (preg_match('~^upload/~i', $relative)) {
        $relative = preg_replace('~^upload/~i', '', $relative) ?? $relative;
        $relative = ltrim($relative, '/');
    }

    $abs = rtrim(alb_upload_root_abs(), '/') . '/' . $relative;
    alb_safe_unlink_under_upload($abs);
}

/* намагаємось прибрати всю папку альбому */
if (is_dir($albumDir)) {
    alb_remove_tree($albumDir);
}

alb_delete_redirect(alb_delete_append_query($back, ['am' => 'deleted']));