<?php
declare(strict_types=1);

/**
 * /functional/albums/create.php
 * Створення фотоальбому користувача.
 *
 * Приймає POST:
 * - csrf
 * - title
 * - description
 * - privacy (public|friends|private)
 * - back (optional)
 *
 * Редіректить назад у профіль/вкладку albums.
 */

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_create_redirect')) {
    function alb_create_redirect(string $url, int $code = 302): void
    {
        header('Location: ' . $url, true, $code);
        exit;
    }
}

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

        $me = alb_me();
        if (!$me || (int)($me['id'] ?? 0) <= 0) {
            $to = '/profile/index.php?tab=albums';
            alb_create_redirect('/login.php?to=' . urlencode($to));
        }
    }
}

if (!function_exists('alb_create_safe_back_url')) {
    function alb_create_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_create_append_query')) {
    function alb_create_append_query(string $url, array $params): string
    {
        $url = trim($url);
        if ($url === '') {
            $url = '/profile/index.php?tab=albums';
        }

        $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_create_require_login();

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

if ($meId <= 0) {
    alb_create_redirect('/login.php');
}

$fallbackBack = alb_profile_albums_url([
    'id'       => $meId,
    'username' => (string)($me['username'] ?? ''),
]);

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

if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    alb_create_redirect($back);
}

if (!alb_ready($pdo)) {
    alb_create_redirect(alb_create_append_query($back, ['am' => 'schema']));
}

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

$title = alb_clean_title((string)($_POST['title'] ?? ''));
$description = alb_clean_description((string)($_POST['description'] ?? ''));
$privacy = alb_privacy_normalize((string)($_POST['privacy'] ?? 'public'));

if ($title === '') {
    alb_create_redirect(alb_create_append_query($back, ['am' => 'title']));
}

$username = trim((string)($me['username'] ?? ''));
if ($username === '') {
    $username = 'user_' . $meId;
}

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

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

    $st = $pdo->prepare("
        INSERT INTO photo_albums
            (user_id, title, description, privacy, created_at, updated_at)
        VALUES
            (?, ?, ?, ?, NOW(), NOW())
    ");
    $st->execute([
        $meId,
        $title,
        $description !== '' ? $description : null,
        $privacy,
    ]);

    $albumId = (int)$pdo->lastInsertId();

    if ($albumId <= 0) {
        throw new RuntimeException('Failed to create album.');
    }

    $albumDir = alb_album_dir_abs($username, $albumId);
    if (!is_dir($albumDir) && !mkdir($albumDir, 0775, true) && !is_dir($albumDir)) {
        throw new RuntimeException('Failed to create album directory.');
    }

    @chmod($albumDir, 0775);

    if ($ownTx) {
        $pdo->commit();
    }
} catch (Throwable $e) {
    if ($ownTx && $pdo->inTransaction()) {
        $pdo->rollBack();
    }

    alb_create_redirect(alb_create_append_query($back, ['am' => 'db']));
}

alb_create_redirect(alb_create_append_query($back, [
    'am'       => 'created',
    'album_id' => $albumId,
]));