repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

814 lines · 72.6 KB · download this file

package BlowfishCMS::Addon::Services;
# Services: a Services page for what you offer, and booking it.
#
# The page (1.0): services each with an anchor of their own (/services/#hosting),
# pricing plans (/services/#pricing) and jump links to every part with an
# anchor, built on BlowfishCMS 0.40's anchors.
#
# Booking (2.0): the owner lists what can be booked on the Offerings screen,
# each with its price (fixed, by the hour, or on request), when it's paid
# (when booking, a deposit, or after the job), where it's done (in person in
# a service area, remotely, or by mail: they send it in and give an address to
# send it back to, 2.3), whether to ask for preferred times, and its
# own questions. Visitors book at /x/services/book/OFFERING/: they answer the
# questions, suggest times, give their details, and pay on Stripe's own page
# when the offering is paid up front (card details never reach this server).
# The owner confirms a time, asks for payment (hours worked, a quote, the rest
# of a deposit) and marks the job done on the Bookings screen; each step is
# emailed through the site's mail queue.
#
# Where each part runs:
#   admin service     Offerings screen (/admin/?kind=x-services): the offerings
#                     and settings, in the catalogue (services_offerings,
#                     addon_settings). No visitor's details are kept there.
#   public service    the blocks on pages.
#   services service  (its own account, _bfxservices) /x/services/book/…, the
#                     booking's page (/x/services/booking/ID?k=KEY), payment
#                     (/x/services/pay/ID?k=KEY, which sends the visitor on to
#                     Stripe), the Stripe webhook, and the Bookings screen
#                     (/admin/x/services/). Only it can read bookings (names,
#                     addresses, answers) and the Stripe keys.
#
# Bookings database (its private folder): bookings (one request each, with a
# random key that opens its page: links are emailed, never guessed), payments
# (each amount asked for: due, pending at Stripe, paid, or cancelled), events
# (Stripe's, so one is acted on once) and webhook_log.
use v5.36;
use utf8;
use JSON::PP ();
use Digest::SHA qw(sha256_hex);
use Encode qw(encode decode);
use POSIX qw(strftime);
use File::Basename qw(dirname);
BEGIN {
    no strict 'refs';
    *{$_}=\&{"BlowfishCMS::$_"} for qw(h param setting site_url own_origin window window_html admin_page end_page start_page fields hidden
        redirect header attempt failed_action clean_error now random_id render_markdown markdown_copy json_ld cta_html link_ok link_fields
        library_img anchor_ok all_pages addon_page post_excerpt addon_setting addon_setting_save addon_data_dir addon_secret_dir mail_queue mail_address_ok eq_safe switch_button switch_field list_order order_list_attrs order_row_attrs drag_handle move_buttons row_menu sort_order_save admin_row admin_list);
}
sub db () { $BlowfishCMS::db }
sub json () { return JSON::PP->new->canonical }

# ---- Money (the core's Payments.pm since 2.1.0), in its currency: "$85", "$45.50" -----------
sub currencies { return BlowfishCMS::currencies() }
sub currency { my $c=addon_setting('services','currency','usd');return $c =~ /\A[a-z]{3}\z/ ? $c : 'usd' }
sub money ($amount,$cur=currency()) { return BlowfishCMS::money($amount,$cur,whole=>1) }
# "12.50" -> 1250 (or 12 for zero-decimal currencies); dies on anything else.
sub parse_money ($text,$what,$cur=currency()) { return BlowfishCMS::parse_money($text,$what,$cur) }
sub money_input ($amount,$cur=currency()) { return BlowfishCMS::money_input($amount,$cur) }

# ---- Offerings (the catalogue; admin service writes them) ------------------------------------
sub migrate ($dbh) {
    $dbh->do("CREATE TABLE IF NOT EXISTS services_offerings (id TEXT PRIMARY KEY, slug TEXT NOT NULL UNIQUE, name TEXT NOT NULL, grp TEXT NOT NULL DEFAULT '',
        summary TEXT NOT NULL DEFAULT '', pricing TEXT NOT NULL DEFAULT 'fixed', amount INTEGER NOT NULL DEFAULT 0, pay TEXT NOT NULL DEFAULT 'now',
        deposit INTEGER NOT NULL DEFAULT 0, place TEXT NOT NULL DEFAULT 'remote', area TEXT NOT NULL DEFAULT '', times INTEGER NOT NULL DEFAULT 1,
        questions TEXT NOT NULL DEFAULT '[]', active INTEGER NOT NULL DEFAULT 1, sort_order INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)");
    $dbh->do('CREATE TABLE IF NOT EXISTS services_seeded (slug TEXT PRIMARY KEY, at TEXT NOT NULL)');
    # down (2.3): a down payment, a share (%) of the price paid before the work starts.
    my %cols=map {($_->[1]=>1)} @{$dbh->selectall_arrayref('PRAGMA table_info(services_offerings)')};
    $dbh->do('ALTER TABLE services_offerings ADD COLUMN down INTEGER NOT NULL DEFAULT 0') unless $cols{down};
    seed($dbh);
}
# Offerings shipped in seed/ (2.3): each seed/NAME.json is {"offerings": [{slug,
# name, grp, summary, pricing, amount (whole units, "45" or "12.50"), pay,
# deposit, down (a % down payment), place, area, times, active, questions: [{label, type, options,
# required}]}], "settings": {key: value}}. Each offering is added once (a
# deleted one isn't added again), after the ones there; a setting is filled
# in only while it's empty.
sub seed ($dbh) {
    opendir my $dh,dirname(__FILE__).'/../seed' or return;
    my %types=map {($_->[0]=>1)} BlowfishCMS::question_kinds();
    for my $file (sort grep {/\A[a-z0-9-]+\.json\z/} readdir $dh) {
        my $s=attempt {open my $fh,'<:raw',dirname(__FILE__)."/../seed/$file" or die;local $/;JSON::PP->new->utf8->decode(scalar <$fh>)} or next;
        for my $o (ref $s->{offerings} eq 'ARRAY' ? @{$s->{offerings}} : ()) {
            my $slug=slugify($o->{slug}//$o->{name});next unless length $slug && length($o->{name}//'');
            next if $dbh->selectrow_array('SELECT 1 FROM services_seeded WHERE slug=?',undef,$slug) || $dbh->selectrow_array('SELECT 1 FROM services_offerings WHERE slug=?',undef,$slug);
            my $cents=sub ($v) {($v//'') =~ /\A(\d+)(?:\.(\d\d))?\z/ ? $1*100+($2//0) : 0};
            my $pricing=($o->{pricing}//'') =~ /\A(?:fixed|hourly|quote)\z/ ? $o->{pricing} : 'fixed';
            my $pay=$pricing eq 'fixed' && ($o->{pay}//'') =~ /\A(?:now|deposit|after)\z/ ? $o->{pay} : 'after';
            my $i=0;my @qs=map {{id=>'q'.++$i,label=>$_->{label}//'',type=>$types{$_->{type}//''} ? $_->{type} : 'text',options=>$_->{options}//'',required=>$_->{required} ? 1 : 0}} grep {length($_->{label}//'')} @{ref $o->{questions} eq 'ARRAY' ? $o->{questions} : []};
            my $order=1+($dbh->selectrow_array('SELECT max(sort_order) FROM services_offerings')//0);
            my $down=($o->{down}//'') =~ /\A\d{1,3}\z/ && $o->{down}<=100 ? 0+$o->{down} : 0;
            $dbh->do('INSERT INTO services_offerings (id,slug,name,grp,summary,pricing,amount,pay,deposit,down,place,area,times,questions,active,sort_order,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',undef,
                substr(random_id(),0,16),$slug,$o->{name},$o->{grp}//'',$o->{summary}//'',$pricing,$pricing eq 'quote' ? 0 : $cents->($o->{amount}),$pay,$pay eq 'deposit' ? $cents->($o->{deposit}) : 0,$down,
                ($o->{place}//'') =~ /\A(?:remote|in_person|mail)\z/ ? $o->{place} : 'remote',$o->{area}//'',$o->{times} ? 1 : 0,json()->encode(\@qs),exists $o->{active} && !$o->{active} ? 0 : 1,$order,now(),now());
            $dbh->do('INSERT INTO services_seeded (slug,at) VALUES (?,?)',undef,$slug,now());
        }
        my %set=ref $s->{settings} eq 'HASH' ? %{$s->{settings}} : ();
        for my $k (grep {/\A(?:currency|terms|note|mail_note|email_owner|email_customer)\z/} sort keys %set) {
            addon_setting_save('services',$k=>$set{$k}) unless length addon_setting('services',$k,'');
        }
    }
}
my %pricing=(fixed=>'A fixed price',hourly=>'By the hour',quote=>'On request (you give a price)');
my %pay=(now=>'When booking',deposit=>'A deposit when booking, the rest after',after=>'After the job');
my %place=(remote=>'Remotely (no address asked)',in_person=>'In person (an address in your service area)',mail=>'By mail (they send it to you; a return address asked)');
my %parts=(any=>'Any time',morning=>'Morning',afternoon=>'Afternoon',evening=>'Evening');
my @part_order=qw(any morning afternoon evening);
sub slugify ($t) { return substr(lc($t//'') =~ s/[^a-z0-9]+/-/gr =~ s/\A-+|-+\z//gr,0,40) =~ s/-+\z//r }
sub offering_row ($o) { return undef unless $o;$o->{qs}=(attempt {JSON::PP->new->decode($o->{questions})}) // [];$o->{qs}=[] unless ref $o->{qs} eq 'ARRAY';return $o }
sub offerings ($active=0) { return [map {offering_row($_)} @{(attempt {db()->selectall_arrayref('SELECT * FROM services_offerings'.($active ? ' WHERE active=1' : '').' ORDER BY sort_order,created_at',{Slice=>{}})}) // []}] }
sub offering ($slug) { return undef unless ($slug//'') =~ /\A[a-z0-9][a-z0-9-]{0,39}\z/;return offering_row(attempt {db()->selectrow_hashref('SELECT * FROM services_offerings WHERE slug=?',undef,$slug)}) }
sub offering_by_id ($id) { return undef unless ($id//'') =~ /\A[a-f0-9]{16}\z/;return offering_row(attempt {db()->selectrow_hashref('SELECT * FROM services_offerings WHERE id=?',undef,$id)}) }
sub area_list ($o) { return grep {length} map {s/\A\s+|\s+\z//gr} split /,/,$o->{area}//'' }
# The price as visitors read it: "$65", "$45/hour", "price on request".
sub price_text ($o) {
    return 'price on request' if $o->{pricing} eq 'quote';
    return money($o->{amount}).'/hour' if $o->{pricing} eq 'hourly';
    return money($o->{amount});
}
# What's paid when booking (0 when nothing is): the price, or the deposit.
sub due_at_booking ($o) {
    return 0 unless $o->{pricing} eq 'fixed';
    # A down payment: its share of the price, in place of Paid and Deposit.
    if (($o->{down}//0)>0) {my $d=int($o->{amount}*$o->{down}/100+0.5);return $d<$o->{amount} ? $d : $o->{amount}}
    return $o->{amount} if $o->{pay} eq 'now';
    return $o->{deposit}>0 && $o->{deposit}<$o->{amount} ? $o->{deposit} : $o->{amount} if $o->{pay} eq 'deposit';
    return 0;
}
# How paying works for it, in a sentence for the booking form.
sub pay_text ($o) {
    my $down=$o->{down}//0;
    return "You’ll get a price for it first, then pay $down% of it as a down payment before the work starts; the rest when it’s done." if $o->{pricing} eq 'quote' && $down>0 && $down<100;
    return 'It’s '.money($o->{amount})." an hour. Before the work starts you’ll get an estimate, and pay $down% of it as a down payment; the rest when it’s done." if $o->{pricing} eq 'hourly' && $down>0 && $down<100;
    return 'You’ll get a price for it before anything is paid.' if $o->{pricing} eq 'quote';
    return 'It’s '.money($o->{amount}).' an hour, paid when the job is done.' if $o->{pricing} eq 'hourly';
    my $due=due_at_booking($o);
    return 'It’s '.money($o->{amount}).', paid when the job is done.' unless $due;
    return 'It’s '.money($o->{amount}).', paid now to book it.' if $due==$o->{amount};
    return 'It’s '.money($o->{amount}).': a '.money($due)." down payment ($down%) now to book it, the rest when the job is done." if $down>0;
    return 'It’s '.money($o->{amount}).': '.money($due).' now to book it, the rest when the job is done.';
}

# ---- Blocks ----------------------------------------------------------------------------------
my @panel=([title=>'Panel title','text',120,'optional'],[subtitle=>'Panel subtitle','text',160,'optional']);
# Booking choices for a service card or the Book block: a group of offerings
# ("g:KEY", a list to choose from) or one offering (its slug).
sub groups { my (%seen,@g);for (@{offerings(1)}) {push @g,$_->{grp} if length $_->{grp} && !$seen{$_->{grp}}++}return @g }
sub book_choices { return ([''=>'No booking button'],(map {['g:'.slugify($_),"Choose from: $_"]} groups()),(map {[$_->{slug},"Book: $_->{name}"]} @{offerings(1)})) }
sub book_href ($v) {
    $v//='';
    if ($v =~ /\Ag:([a-z0-9-]{1,40})\z/) {my $g=$1;return (grep {slugify($_->{grp}) eq $g} @{offerings(1)}) ? "/x/services/book/?g=$g" : ''}
    my $o=offering($v);return $o && $o->{active} ? "/x/services/book/$o->{slug}/" : '';
}
sub blocks {
    my @book=book_choices();
    return {
        services_list=>{label=>'Services',order=>64,group=>'content',
            about=>'What you offer: each service with a picture, a few words, its price, a button and an anchor of its own (/services/#hosting).',
            fields=>[@panel,
                [layout=>'Layout','select',[[cards=>'Cards side by side'],[rows=>'One under another, the picture beside the words']]],
                [count=>'Cards in a row','select',[[2=>'Two'],[3=>'Three']]],
                [book_label=>'Booking buttons say','text',40,'such as “Book”'],
                [services=>'Services','items',[[name=>'Name','text',120],
                    [anchor=>'Anchor','text',40,'optional; a name such as hosting, so links can jump to it: /services/#hosting'],
                    [picture=>'Picture','picture'],[summary=>'About it','markdown',3000,'optional'],
                    [price=>'Price','text',80,'optional; such as “from $10 a month”'],
                    [book=>'Booking','select',\@book,'optional; a button to book it (what can be booked is on the Offerings tab)'],
                    [button=>'Button','text',60,'optional; such as “Ask about it”'],link_fields('link','Button links to')]]],
            defaults=>{title=>'services',layout=>'cards',count=>2,book_label=>'Book',services=>[{name=>'A service',anchor=>'',summary=>'A few words about it.',price=>'',button=>'Ask about it',link=>'/contact/'}]},
            render=>\&list_html},
        services_pricing=>{label=>'Pricing',order=>65,group=>'content',
            about=>'Plans side by side, each with its price, what’s included and a button; one can stand out. Its anchor starts as “pricing” (/services/#pricing).',
            fields=>[@panel,
                [plans=>'Plans','items',[[name=>'Plan','text',80],[price=>'Price','text',40,'such as “$10”'],
                    [period=>'Per','text',40,'optional; such as “a month” or “a repair”'],[about=>'Under the price','text',200,'optional; a line about it'],
                    [features=>'What’s included','markdown',2000,'optional; one per line, each starting with “- ”'],
                    [featured=>'Make this plan stand out','check'],[badge=>'Its label','text',40,'optional; such as “most popular”'],
                    [button=>'Button','text',60,'optional'],link_fields('link','Button links to')]],
                [note=>'Under the plans','markdown',1000,'optional; such as “Prices include tax.”']],
            defaults=>{title=>'pricing',section_anchor=>'pricing',plans=>[
                {name=>'Basic',price=>'$10',period=>'a month',features=>"- One thing\n- Another",button=>'Choose Basic',link=>'/contact/'},
                {name=>'Full',price=>'$20',period=>'a month',features=>"- Everything in Basic\n- And more",featured=>1,badge=>'most popular',button=>'Choose Full',link=>'/contact/'}]},
            render=>\&pricing_html},
        services_jump=>{label=>'Jump links',order=>66,group=>'content',
            about=>'Links to each part of the page that has an anchor (each service and the pricing too), made for you as the page changes.',
            fields=>[[title=>'Panel title','text',120,'optional'],[intro=>'Before the links','text',80,'optional; such as “Jump to:”'],
                [style=>'Look','select',[[buttons=>'Buttons'],[links=>'Links in a line']]]],
            defaults=>{title=>'',intro=>'Jump to:',style=>'buttons'},
            render=>\&jump_html},
        services_book=>{label=>'Book a service',order=>67,group=>'content',
            about=>'What can be booked (from the Offerings tab), each with its price and a button that opens its booking form. Its anchor starts as “book”.',
            fields=>[@panel,[group=>'Show','select',[[''=>'Everything that can be booked'],map {['g:'.slugify($_),"Only: $_"]} groups()]],
                [intro=>'Above the list','markdown',2000,'optional'],[button=>'Buttons say','text',40]],
            defaults=>{title=>'book',section_anchor=>'book',button=>'Book'},
            render=>\&book_block_html},
    };
}
# A list field's entries (hashes only, whatever is stored).
sub list ($v) { return grep {ref eq 'HASH'} @{ref $v eq 'ARRAY' ? $v : []} }
# A service's anchor as typed ("#Web hosting") made into one (web-hosting),
# or '' when it isn't usable (BlowfishCMS::anchor_ok keeps the page's own ids).
sub anchor_of ($v) { my $name=lc($v//'') =~ s/\A#+//r =~ s/[\s_]+/-/gr =~ s/\A-+|-+\z//gr;return anchor_ok($name) ? $name : '' }
# A block's button: cta_html, when it has words and a usable address.
sub button ($e,%o) { return length($e->{button}//'') && link_ok($e->{link}) ? cta_html($e->{button},$e->{link},%o,newtab=>$e->{link_newtab}) : '' }
# The services that have a name, each with its anchor (the first use of an
# anchor in the block only).
sub services ($d) {
    my %seen;
    return map {my $name=anchor_of($_->{anchor});$name='' if length $name && $seen{$name}++;+{%$_,anchor=>$name}} grep {length($_->{name}//'')} list($d->{services});
}

sub list_html ($b,%o) {
    my $d=$b->{data};my @s=services($d);
    return '' unless @s;
    my $rows=($d->{layout}//'') eq 'rows';
    my $html=join '',map {
        my $img=library_img($_->{picture},'',class=>'service__picture');my $href=book_href($_->{book});
        my $btn=join ' ',grep {length} ($href ? cta_html(length($d->{book_label}//'') ? $d->{book_label} : 'Book',$href,style=>'primary') : ''),button($_,style=>$href ? 'outline' : 'primary');
        '<article class="service"'.(length $_->{anchor} ? qq{ id="$_->{anchor}"} : '').'>'.($img//'')
            .'<div class="service__text"><h3 class="service__name">'.h($_->{name}).'</h3>'
            .(length($_->{price}//'') ? '<p class="service__price">'.h($_->{price}).'</p>' : '')
            .markdown_copy($_->{summary})
            .(length $btn ? '<p class="service__button">'.$btn.'</p>' : '')
            .'</div></article>'
    } @s;
    my $class=$rows ? 'services services--rows' : 'services services--cards services--'.(($d->{count}//'2') eq '3' ? 3 : 2);
    return window_html($d->{title},$d->{subtitle},'<div class="'.$class.'">'.$html.'</div>'.structured(@s),%o,nobar=>($o{nobar} || !length($d->{title}//'')));
}
# The services for search engines: an ItemList of Services, each with its
# address on the page and a word about it.
sub structured (@s) {
    my $page=addon_page('services');my $base=$page ? site_url().$page->{path} : '';
    return json_ld({'@type'=>'ItemList',itemListElement=>[map {
        my $s=$s[$_];my $about=post_excerpt($s->{summary}//'');
        {'@type'=>'ListItem',position=>$_+1,item=>{'@type'=>'Service',name=>$s->{name},
            (length $base && length $s->{anchor} ? (url=>"$base#$s->{anchor}") : ()),(length $about ? (description=>$about) : ())}}
    } 0..$#s]});
}

sub pricing_html ($b,%o) {
    my $d=$b->{data};my @p=grep {length($_->{name}//'')} list($d->{plans});
    return '' unless @p;
    my $html=join '',map {
        my $f=$_->{featured};my $btn=button($_,style=>$f ? 'primary' : 'outline',fill=>'full');
        '<article class="plan'.($f ? ' plan--featured' : '').'">'
            .(length($_->{badge}//'') ? '<p class="plan__badge">'.h($_->{badge}).'</p>' : '')
            .'<h3 class="plan__name">'.h($_->{name}).'</h3>'
            .(length($_->{price}//'') ? '<p class="plan__price"><span class="plan__amount">'.h($_->{price}).'</span>'.(length($_->{period}//'') ? ' <span class="plan__period">'.h($_->{period}).'</span>' : '').'</p>' : '')
            .(length($_->{about}//'') ? '<p class="plan__about">'.h($_->{about}).'</p>' : '')
            .(length($_->{features}//'') ? '<div class="plan__features">'.render_markdown($_->{features}).'</div>' : '')
            .(length $btn ? '<p class="plan__button">'.$btn.'</p>' : '')
            .'</article>'
    } @p;
    return window_html($d->{title},$d->{subtitle},'<div class="plans plans--'.(@p>4 ? 4 : scalar @p).'">'.$html.'</div>'.markdown_copy($d->{note}),
        %o,nobar=>($o{nobar} || !length($d->{title}//'')));
}

# The parts of the page with an anchor, in the page's order: each block's
# own (named by its title or heading, else by the anchor itself) and each
# service's (named by the service). Read from the page as it was last saved.
sub targets ($b) {
    my ($page)=grep {my $p=$_;grep {$_->{id} eq $b->{id}} @{$p->{blocks}//[]}} @{all_pages()};
    return () unless $page;
    my (@t,%seen);
    for my $x (@{$page->{blocks}}) {
        next if $x->{id} eq $b->{id};
        my $xd=$x->{data};my $anchor=$xd->{section_anchor}//'';
        if (anchor_ok($anchor)) {
            my ($name)=grep {length} map {$xd->{$_}//''} qw(title heading label);
            push @t,[$anchor,$name//ucfirst($anchor =~ tr/-/ /r)] unless $seen{$anchor}++;
        }
        if ($x->{type} eq 'services_list') {push @t,map {[$_->{anchor},$_->{name}]} grep {length $_->{anchor} && !$seen{$_->{anchor}}++} services($xd)}
    }
    return @t;
}
sub jump_html ($b,%o) {
    my $d=$b->{data};my @t=targets($b);
    return '' unless @t;
    my $buttons=($d->{style}//'buttons') ne 'links';
    my $links=join '',map {$buttons ? cta_html(ucfirst $_->[1],"#$_->[0]",style=>'outline',size=>'small') : '<a href="#'.h($_->[0]).'">'.h(ucfirst $_->[1]).'</a>'} @t;
    my $nav='<nav class="services-jump services-jump--'.($buttons ? 'buttons' : 'links').'" aria-label="On this page">'
        .(length($d->{intro}//'') ? '<span class="services-jump__intro">'.h($d->{intro}).'</span>' : '').$links.'</nav>';
    return window_html($d->{title},'',$nav,%o,nobar=>($o{nobar} || !length($d->{title}//'')));
}

# What can be booked, in its groups, each with its price and a button.
sub book_list_html ($gkey,$button) {
    my @o=grep {!length $gkey || slugify($_->{grp}) eq $gkey} @{offerings(1)};
    return '<p class="empty-media">Nothing can be booked here yet.</p>' unless @o;
    my (@groups,%in);
    for (@o) {push @groups,$_->{grp} unless $in{$_->{grp}};push @{$in{$_->{grp}}},$_}
    return join '',map {my $g=$_;
        (length $g ? '<h3 class="booking-group">'.h($g).'</h3>' : '').'<ul class="booking-list">'.join('',map {
            '<li class="booking-item"><div class="booking-item__text"><p class="booking-item__name"><strong>'.h($_->{name}).'</strong> <span class="booking-item__price">'.h(price_text($_)).'</span></p>'
            .markdown_copy($_->{summary}).'</div>'.cta_html(length($button//'') ? $button : 'Book',"/x/services/book/$_->{slug}/",style=>'primary').'</li>'} @{$in{$g}}).'</ul>'} @groups;
}
sub book_block_html ($b,%o) {
    my $d=$b->{data};my ($g)=($d->{group}//'') =~ /\Ag:([a-z0-9-]{1,40})\z/;
    return window_html($d->{title},$d->{subtitle},markdown_copy($d->{intro}).book_list_html($g//'',$d->{button}),%o,nobar=>($o{nobar} || !length($d->{title}//'')));
}

# ---- Offerings screen (admin service, /admin/?kind=x-services) -----------------------------------
sub admin {
    my $message=param('notice',2000);my $edit=offering_by_id(param('edit',16) || param('id',16));
    my $back=sub ($n,$id='') {redirect('/admin/?kind=x-services&notice='.CGI::escape(encode('UTF-8',$n)).(length $id ? "&edit=$id" : ''))};
    if ($BlowfishCMS::method eq 'POST') {
        # The editor's save button sends the form in the background (admin.js)
        # and wants JSON back; without the script it's an ordinary post.
        my $fetch=BlowfishCMS::fetch_request();
        attempt {
            my $action=param('action',30);
            list_order(ids=>[map {$_->{id}} @{offerings()}],back=>'/admin/?kind=x-services',
                save=>sub (@ids) {sort_order_save(db(),'services_offerings','id',@ids)});
            if ($action eq 'offering_new') {
                my $name=param('name',120);die "Give it a name.\n" unless length $name;
                my $slug=slugify($name) || 'service';my $n=1;
                while (offering($slug)) {$slug=substr(slugify($name) || 'service',0,36).'-'.++$n}
                my $id=substr(random_id(),0,16);
                my $order=1+(db()->selectrow_array('SELECT max(sort_order) FROM services_offerings')//0);
                my $qs=[{id=>'q1',label=>'What do you need done?',type=>'long',required=>1,options=>''}];
                db()->do('INSERT INTO services_offerings (id,slug,name,questions,active,sort_order,created_at,updated_at) VALUES (?,?,?,?,0,?,?,?)',undef,$id,$slug,$name,json()->encode($qs),$order,now(),now());
                $back->("Made $name. Set its price and questions, then tick “Can be booked”.",$id);
            }
            if ($action eq 'offering_save') {
                $edit or die "That offering no longer exists.\n";
                my %v=(name=>param('name',120),grp=>param('grp',80),summary=>param('summary',3000),area=>param('area',600),
                    times=>param('times',1) eq '1' ? 1 : 0,active=>param('active',1) eq '1' ? 1 : 0);
                $v{summary} =~ s/\r\n?/\n/g;
                die "Give it a name.\n" unless length $v{name};
                my $slug=slugify(param('slug',40));
                die "Address: letters, numbers and dashes, such as pc-repair.\n" unless $slug =~ /\A[a-z0-9][a-z0-9-]{0,39}\z/;
                my $other=offering($slug);die "Another offering is at /x/services/book/$slug/.\n" if $other && $other->{id} ne $edit->{id};
                $v{slug}=$slug;
                $v{pricing}=param('pricing',10);die "Choose how it’s priced.\n" unless $pricing{$v{pricing}};
                $v{pay}=param('pay',10);die "Choose when it’s paid.\n" unless $pay{$v{pay}};
                $v{place}=param('place',10);die "Choose where it’s done.\n" unless $place{$v{place}};
                $v{amount}=$v{pricing} eq 'quote' ? 0 : parse_money(param('amount',20),$v{pricing} eq 'hourly' ? 'Hourly rate' : 'Price');
                die "Price: Stripe needs at least 0.50 (or about that in your currency).\n" if $v{pricing} ne 'quote' && $v{amount}<50;
                my $dep=param('deposit',20);
                $v{deposit}=$v{pricing} eq 'fixed' && $v{pay} eq 'deposit' ? parse_money($dep,'Deposit') : 0;
                die "Deposit: more than 0.50 and less than the price.\n" if $v{pricing} eq 'fixed' && $v{pay} eq 'deposit' && ($v{deposit}<50 || $v{deposit}>=$v{amount});
                $v{pay}='after' unless $v{pricing} eq 'fixed';
                my $down=param('down',3);$v{down}=length $down ? $down : 0;
                die "Down payment: a whole number from 0 to 100 (%), or leave it empty.\n" unless $v{down} =~ /\A\d{1,3}\z/ && $v{down}<=100;
                # A question keeps its id while its words stay the same, so bookings line up.
                my @qs=@{BlowfishCMS::questions_from_form($edit->{id},$edit->{qs},max=>30)};
                db()->do('UPDATE services_offerings SET slug=?,name=?,grp=?,summary=?,pricing=?,amount=?,pay=?,deposit=?,down=?,place=?,area=?,times=?,questions=?,active=?,updated_at=? WHERE id=?',undef,
                    @v{qw(slug name grp summary pricing amount pay deposit down place area times)},json()->encode(\@qs),$v{active},now(),$edit->{id});
                BlowfishCMS::json_response({ok=>JSON::PP::true,message=>"Saved $v{name}."}) if $fetch;
                $back->("Saved $v{name}.",$edit->{id});
            }
            if ($action eq 'offering_active') {
                $edit or die "That offering no longer exists.\n";my $on=param('on',1) eq '1' ? 1 : 0;
                db()->do('UPDATE services_offerings SET active=?,updated_at=? WHERE id=?',undef,$on,now(),$edit->{id});
                $back->($on ? "$edit->{name} can be booked." : "$edit->{name} is closed for booking; it stays here.");
            }
            if ($action eq 'offering_delete') {
                $edit or die "That offering no longer exists.\n";
                db()->do('DELETE FROM services_offerings WHERE id=?',undef,$edit->{id});
                $back->("Deleted $edit->{name}. Its bookings stay on the Bookings screen.");
            }
            if ($action eq 'booking_settings') {
                my $cur=param('currency',3);die "Choose a currency.\n" unless grep {$_ eq $cur} currencies();
                my $terms=param('terms',3000);my $note=param('note',1000);my $mail_note=param('mail_note',1000);s/\r\n?/\n/g for $terms,$note,$mail_note;
                addon_setting_save('services',currency=>$cur,terms=>$terms,note=>$note,mail_note=>$mail_note,
                    email_owner=>param('email_owner',1) eq '1' ? 1 : 0,email_customer=>param('email_customer',1) eq '1' ? 1 : 0);
                $back->('Booking settings saved.');
            }
            die "Choose an action.\n";
        } or do {$message=failed_action($@);BlowfishCMS::json_response({ok=>JSON::PP::false,message=>$message},400) if $fetch};
    }
    my $css='<link rel="stylesheet" href="/addons/services/services.css?v=2.0.0">';
    if ($edit) {
        admin_page('Offerings',section=>'x-services',notice=>$message,save=>['save','All changes saved'],
            intro=>'<a href="/admin/?kind=x-services">All offerings</a> · Booked at <a href="/x/services/book/'.h($edit->{slug}).'/" target="_blank" rel="noopener">/x/services/book/'.h($edit->{slug}).'/</a>'.($edit->{active} ? '' : ' (once “Can be booked” is ticked)').'.');
        print $css;
        print '<form id="bulk-edit" method="post" action="/admin/" class="admin-form">'.fields('offering_save','x-services',$edit->{id}).'</form>';
        my $in=sub ($n,$l,$v,$max,$hint='',%a) {'<label>'.h($l).'<input name="'.$n.'" value="'.h($v).'" maxlength="'.$max.'" form="bulk-edit"'.($a{mode} ? ' inputmode="'.$a{mode}.'"' : '').'>'.($hint ? '<span class="optional">'.h($hint).'</span>' : '').'</label>'};
        my $sel=sub ($n,$l,$v,$map,$order,$hint='') {'<label>'.h($l).'<select name="'.$n.'" form="bulk-edit">'.join('',map {'<option value="'.$_.'"'.($_ eq $v ? ' selected' : '').'>'.h($map->{$_}).'</option>'} @$order).'</select>'.($hint ? '<span class="optional">'.h($hint).'</span>' : '').'</label>'};
        my $check=sub ($n,$l,$on,$hint='') {switch_field($n,$l,$on,form=>'bulk-edit',hint=>$hint)};
        my $cur=currency();
        window('the offering','<div class="admin-form block-card__fields">'.$in->('name','Name',$edit->{name},120,'as visitors see it, such as “Windows reinstall”')
            .$in->('grp','Group',$edit->{grp},80,'optional; offerings with the same group are listed together, such as “Computer & laptop help”')
            .$in->('slug','Address',$edit->{slug},40,'its booking form is at /x/services/book/ADDRESS/')
            .'<label class="block-wide">About it<textarea name="summary" rows="3" maxlength="3000" form="bulk-edit" data-markdown>'.h($edit->{summary}).'</textarea><span class="optional">Optional, shown in the list and on its booking form (Markdown).</span></label>'
            .$check->('active','Can be booked',$edit->{active},'Shown in lists, and its form is open.').'</div>');
        window('price and payment','<div class="admin-form block-card__fields">'
            .$sel->('pricing','Priced',$edit->{pricing},\%pricing,[qw(fixed hourly quote)])
            .$in->('amount','Price, or hourly rate ('.uc($cur).')',$edit->{pricing} eq 'quote' || !$edit->{amount} ? '' : money_input($edit->{amount}),20,'such as 65 or 45.50; not needed for a price on request',mode=>'decimal')
            .$sel->('pay','Paid',$edit->{pay},\%pay,[qw(now deposit after)],'for a fixed price; by the hour and on request are paid after, from a link you send')
            .$in->('deposit','Deposit ('.uc($cur).')',$edit->{deposit} ? money_input($edit->{deposit}) : '',20,'for “a deposit when booking”',mode=>'decimal')
            .$in->('down','Down payment (%)',$edit->{down} ? $edit->{down} : '',3,'optional; such as 50. A fixed price takes it when booking, in place of Paid and Deposit; by the hour or on request, you ask for it on the Bookings tab once you’ve given an estimate or price',mode=>'numeric')
            .'<p class="media-label block-wide">Payments go through Stripe (keys on the Bookings tab). Anything paid after the job is asked for from the booking: you enter the hours or the price, and the customer gets a link to pay.</p></div>');
        window('where and when','<div class="admin-form block-card__fields">'
            .$sel->('place','Done',$edit->{place},\%place,[qw(remote in_person mail)])
            .$in->('area','Service area',$edit->{area},600,'for in person: the towns you go to, separated by commas, such as “Overton, Logandale”; leave empty for anywhere')
            .$check->('times','Ask for times that suit them (you confirm one)',$edit->{times}).'</div>');
        window('questions','<p class="media-label">What you need to know to do the job. Every booking also asks for a name, an email address, a phone number (in person), the address (in person) and the times (when asked for).</p><div class="admin-form block-card__fields">'.BlowfishCMS::questions_editor_html($edit->{id},$edit->{qs}).'</div>'.BlowfishCMS::markdown_help_html());
        window('delete','<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Delete $edit->{name}? Its bookings stay on the Bookings screen.").'">'.fields('offering_delete','x-services',$edit->{id}).'<button class="buttonlike danger">delete this offering</button></form>');
        end_page();return 1;
    }
    admin_page('Offerings',section=>'x-services',notice=>$message,
        intro=>'What people can book. Put a <strong>Book a service</strong> block on a page, or give a service card a booking button. Requests arrive on the Bookings tab.');
    print $css;
    my $list=offerings();
    my $i=0;
    window('offerings',admin_list([map {my $o=$_;$i++;
        admin_row(title=>$o->{name},order=>$o->{id},off=>!$o->{active},
            meta=>[(length $o->{grp} ? h($o->{grp}) : ()),h(price_text($o)),h($place{$o->{place}} =~ s/ \(.*//r),($o->{active} ? () : 'not open for booking')],
            actions=>switch_button('x-services','offering_active',$o->{id},$o->{active},'can be booked',what=>'Can be booked',name=>$o->{name})
                .'<a class="buttonlike" href="/admin/?kind=x-services&amp;edit='.h($o->{id}).'">edit</a>',
            menu=>move_buttons('x-services',$o->{id},$i,scalar @$list,label=>$o->{name})
                .'<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Delete $o->{name}? Its bookings stay on the Bookings screen.").'">'.fields('offering_delete','x-services',$o->{id}).'<button class="text-button danger">delete</button></form>')} @$list],
        order=>'x-services',empty=>'No offerings yet. Add the first one below.'));
    window('new offering','<form method="post" action="/admin/" class="admin-form inline-form">'.fields('offering_new','x-services').'<label>Name<input name="name" maxlength="120" required placeholder="Windows reinstall"></label><button class="buttonlike is-primary" type="submit">add offering</button></form><p class="media-label">It starts closed, with one question; set its price and questions, then open it for booking.</p>');
    my $cur=currency();
    window('booking settings','<form method="post" action="/admin/" class="admin-form">'.fields('booking_settings','x-services')
        .'<label>Currency<select name="currency">'.join('',map {'<option value="'.$_.'"'.($_ eq $cur ? ' selected' : '').'>'.uc($_).'</option>'} currencies()).'</select><span class="optional">Prices and payments are in this currency.</span></label>'
        .'<label>Terms<textarea name="terms" rows="3" maxlength="3000" data-markdown>'.h(addon_setting('services','terms','')).'</textarea><span class="optional">Optional (Markdown). When set, they’re shown on every booking form, and people tick that they agree.</span></label>'
        .'<label>Sending things by mail<textarea name="mail_note" rows="3" maxlength="1000" data-markdown>'.h(addon_setting('services','mail_note','')).'</textarea><span class="optional">For offerings done by mail: where to send it and how to pack it, shown when booking and in the confirmation (Markdown).</span></label>'
        .'<label>A note for confirmations<textarea name="note" rows="2" maxlength="1000">'.h(addon_setting('services','note','')).'</textarea><span class="optional">Optional, added to the email people get when they book, such as how to get ready.</span></label>'
        .switch_field('email_owner','Email me each booking and payment',addon_setting('services','email_owner',1))
        .switch_field('email_customer','Email customers at each step',addon_setting('services','email_customer',1),hint=>'Request received, time confirmed, payment asked for and received.')
        .'<p class="media-label">Emails go through the site’s Postmark connection (Settings → Mail): yours to the update alerts address, or else where contact messages go.</p>'
        .'<button class="buttonlike" type="submit">save</button></form>'.BlowfishCMS::markdown_help_html());
    end_page();
    return 1;
}

# ---- Bookings (the services service) --------------------------------------------------------------
sub bookings_db {
    state %open;my $file=addon_data_dir('services').'/bookings.sqlite';
    return $open{$file} if $open{$file} && $open{$file}->ping;
    my $b=DBI->connect("dbi:SQLite:dbname=$file",'','',{RaiseError=>1,PrintError=>0,AutoCommit=>1,sqlite_unicode=>1});
    $b->do('PRAGMA busy_timeout=5000');
    $b->do("CREATE TABLE IF NOT EXISTS bookings (id TEXT PRIMARY KEY, k TEXT NOT NULL, offering TEXT NOT NULL, offering_name TEXT NOT NULL, pricing TEXT NOT NULL,
        amount INTEGER NOT NULL DEFAULT 0, currency TEXT NOT NULL, place TEXT NOT NULL, name TEXT NOT NULL, email TEXT NOT NULL, phone TEXT NOT NULL DEFAULT '',
        street TEXT NOT NULL DEFAULT '', town TEXT NOT NULL DEFAULT '', times TEXT NOT NULL DEFAULT '[]', answers TEXT NOT NULL DEFAULT '[]', notes TEXT NOT NULL DEFAULT '',
        status TEXT NOT NULL DEFAULT 'requested', confirmed_time TEXT NOT NULL DEFAULT '', visitor TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL, updated_at TEXT NOT NULL)");
    $b->do('CREATE INDEX IF NOT EXISTS bookings_status ON bookings(status,created_at)');
    $b->do("CREATE TABLE IF NOT EXISTS payments (id TEXT PRIMARY KEY, booking TEXT NOT NULL, amount INTEGER NOT NULL, currency TEXT NOT NULL, purpose TEXT NOT NULL,
        note TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'due', session TEXT NOT NULL DEFAULT '', live INTEGER NOT NULL DEFAULT 0, how TEXT NOT NULL DEFAULT '',
        created_at TEXT NOT NULL, paid_at TEXT)");
    $b->do('CREATE INDEX IF NOT EXISTS payments_booking ON payments(booking)');
    $b->do('CREATE TABLE IF NOT EXISTS events (id TEXT PRIMARY KEY, type TEXT NOT NULL, received_at TEXT NOT NULL)');
    $b->do('CREATE TABLE IF NOT EXISTS webhook_log (id INTEGER PRIMARY KEY CHECK(id=1), ok INTEGER NOT NULL, text TEXT NOT NULL, at TEXT NOT NULL)');
    return $open{$file}=$b;
}
sub booking ($id) { return ($id//'') =~ /\A[a-f0-9]{32}\z/ ? bookings_db()->selectrow_hashref('SELECT * FROM bookings WHERE id=?',undef,$id) : undef }
sub payments_of ($id) { return bookings_db()->selectall_arrayref('SELECT * FROM payments WHERE booking=? ORDER BY created_at',{Slice=>{}},$id) }
sub paid_total ($id) { return bookings_db()->selectrow_array("SELECT coalesce(sum(amount),0) FROM payments WHERE booking=? AND status='paid'",undef,$id)//0 }
sub decoded ($text) { my $v=(attempt {JSON::PP->new->decode($text//'')}) // [];return ref $v eq 'ARRAY' ? $v : [] }
sub booking_url ($b,%o) { return site_url()."/x/services/booking/$b->{id}?k=$b->{k}".($o{paid} ? '&paid=1' : '') }
sub admin_url ($b) { return site_url()."/admin/x/services/?b=$b->{id}" }
my %purpose=(price=>'the price',deposit=>'the deposit',balance=>'the rest',hours=>'hours worked',quote=>'the price',other=>'a payment');
my %status=(requested=>'requested',confirmed=>'time confirmed',done=>'done',cancelled=>'cancelled');
sub times_text ($b) { return join "\n",map {pretty_date($_->{date}).', '.lc($parts{$_->{part}}//'any time')} @{decoded($b->{times})} }
# Everything a booking holds, as text for the emails.
sub booking_text ($b) {
    my $t="$b->{offering_name}\n";
    $t.='Name: '.$b->{name}."\nEmail: ".$b->{email}."\n";
    $t.='Phone: '.$b->{phone}."\n" if length $b->{phone};
    $t.='Address: '.join(', ',grep {length} $b->{street},$b->{town})."\n" if $b->{place} eq 'in_person';
    $t.='Send it back to: '.join(', ',grep {length} $b->{street},$b->{town})."\n" if $b->{place} eq 'mail';
    my $w=times_text($b);
    $t.=length $b->{confirmed_time} ? "Time: $b->{confirmed_time}\n" : length $w ? "Times that suit:\n".($w =~ s/^/  /gmr)."\n" : '';
    for (@{decoded($b->{answers})}) {$t.="$_->{label}:\n".(length $_->{value} ? $_->{value} =~ s/^/  /gmr : '  (no answer)')."\n"}
    $t.="Anything else:\n".($b->{notes} =~ s/^/  /gmr)."\n" if length $b->{notes};
    return $t;
}
sub site_name { return setting('site_title') }
sub email_owner ($subject,$text,%o) { attempt {mail_queue('services',to=>'owner',subject=>$subject,text=>$text,tag=>'services',%o)} if addon_setting('services','email_owner',1) }
sub email_customer ($b,$subject,$text) {
    return unless addon_setting('services','email_customer',1) && mail_address_ok($b->{email});
    my $first=(split ' ',$b->{name})[0]//'';
    attempt {mail_queue('services',to=>$b->{email},reply_to=>'owner',from_name=>site_name(),tag=>'services-customer',subject=>$subject,
        text=>'Hello'.(length $first ? " $first" : '').",\n\n$text\n\nYour booking: ".booking_url($b)."\n\n".site_name()."\n".site_url()."\n")};
}
sub message_page ($title,$text,$status=200) {
    start_page($title,'/x/services/',$status,{noindex=>1});
    window(lc $title,'<h1>'.h($title).'</h1>'.$text);
    end_page();
}
sub route ($rest) {
    if ($rest eq 'book' || $rest eq 'book/') {
        my ($g)=(param('g',40)//'') =~ /\A([a-z0-9-]{1,40})\z/;
        start_page('Book','/x/services/book/',200,{description=>'Book a service.'});
        window('book','<h1>Book</h1><p>Choose what you need.</p>'.book_list_html($g//'','Book'));
        end_page();return 1;
    }
    if ($rest =~ m{\Abook/([a-z0-9][a-z0-9-]{0,39})/?\z}) {my $slug=$1;return booking_form($slug)}
    if ($rest =~ m{\Abooking/([a-f0-9]{32})\z}) {my $id=$1;return booking_page($id)}
    if ($rest =~ m{\Apay/([a-f0-9]{32})\z}) {my $id=$1;return pay($id)}
    if ($rest eq 'webhook') {webhook();return 1}
    return 0;
}
# Bookings' and payments' pages are private: their addresses carry a key.
sub robots { return ['/x/services/booking/','/x/services/pay/'] }

# ---- The booking form (its questions drawn and checked by the core's Questions.pm) ----
sub booking_form ($slug) {
    my $o=offering($slug);
    return 0 unless $o && $o->{active};
    my $problem='';
    $problem=submit($o) if $BlowfishCMS::method eq 'POST';
    my $posted=$BlowfishCMS::method eq 'POST';
    my $val=sub ($n,$max=300) {$posted ? param($n,$max) : ''};
    my $in_person=$o->{place} eq 'in_person';my $mail=$o->{place} eq 'mail';my @area=area_list($o);
    my $today=strftime('%Y-%m-%d',localtime);
    my $form='<form class="booking-form" method="post" action="/x/services/book/'.h($o->{slug}).'/">'
        .hidden(t=>time()).'<label class="booking-trap" aria-hidden="true">Leave this empty<input name="website" tabindex="-1" autocomplete="off"></label>';
    $form.='<fieldset><legend>What you need</legend>'.join('',map {BlowfishCMS::question_html($_,id=>'svc',value=>$posted ? BlowfishCMS::question_posted($_) : '')} @{$o->{qs}}).'</fieldset>' if @{$o->{qs}};
    if ($o->{times}) {
        $form.='<fieldset><legend>When suits you</legend><p class="booking-hint">Up to three times; you’ll get an email when one is confirmed.</p>'
            .join('',map {my $i=$_;'<div class="booking-time"><label>'.($i==1 ? 'First choice' : $i==2 ? 'Second choice' : 'Third choice').'<input type="date" name="d'.$i.'" min="'.$today.'" value="'.h($val->("d$i",10)).'"'.($i==1 ? ' required' : '').'></label>'
                .'<label>Time of day<select name="p'.$i.'">'.join('',map {'<option value="'.$_.'"'.($val->("p$i",10) eq $_ ? ' selected' : '').'>'.$parts{$_}.'</option>'} @part_order).'</select></label></div>'} 1..3).'</fieldset>';
    }
    if ($in_person) {
        $form.='<fieldset><legend>Where</legend><label>Street address<input name="street" maxlength="200" autocomplete="street-address" required value="'.h($val->('street',200)).'"></label>'
            .(@area ? '<label>Town<select name="town" required><option value="">Choose…</option>'.join('',map {'<option'.($val->('town',80) eq $_ ? ' selected' : '').'>'.h($_).'</option>'} @area).'</select><span class="optional">The area served in person: '.h(join(', ',@area)).'.</span></label>'
                : '<label>Town<input name="town" maxlength="80" autocomplete="address-level2" required value="'.h($val->('town',80)).'"></label>').'</fieldset>';
    }
    if ($mail) {
        my $how=addon_setting('services','mail_note','');
        $form.='<fieldset><legend>Sending it</legend>'.(length $how ? '<div class="booking-hint">'.render_markdown($how).'</div>' : '<p class="booking-hint">You’ll get where to send it when your booking is confirmed.</p>')
            .'<label>Return address<input name="street" maxlength="200" autocomplete="street-address" required value="'.h($val->('street',200)).'"><span class="optional">Where to send it back.</span></label>'
            .'<label>Town, state and postcode<input name="town" maxlength="80" autocomplete="address-level2" required value="'.h($val->('town',80)).'"></label></fieldset>';
    }
    $form.='<fieldset><legend>Your details</legend><label>Name<input name="name" maxlength="120" autocomplete="name" required value="'.h($val->('name',120)).'"></label>'
        .'<label>Email<input type="email" name="email" maxlength="200" autocomplete="email" required value="'.h($val->('email',200)).'"></label>'
        .'<label>Phone'.($in_person ? '' : ' <span class="optional">(optional)</span>').'<input type="tel" name="phone" maxlength="30" autocomplete="tel"'.($in_person ? ' required' : '').' value="'.h($val->('phone',30)).'"></label>'
        .'<label>Anything else? <span class="optional">(optional)</span><textarea name="notes" rows="3" maxlength="3000">'.h($val->('notes',3000)).'</textarea></label></fieldset>';
    my $terms=addon_setting('services','terms','');
    $form.='<div class="booking-terms">'.render_markdown($terms).'<label class="booking-check"><input type="checkbox" name="agree" value="1" required> I agree to these terms</label></div>' if length $terms;
    my $due=due_at_booking($o);
    $form.='<p class="booking-pay">'.h(pay_text($o)).'</p><p><button class="cta cta--primary" type="submit">'.($due ? 'Book and go to payment' : 'Send booking request').'</button></p></form>';
    start_page("Book: $o->{name}","/x/services/book/$o->{slug}/",length $problem ? 400 : 200,{description=>post_excerpt($o->{summary}) || "Book $o->{name}."});
    window('book','<p class="booking-crumbs"><a href="/x/services/book/">Book</a>'.(length $o->{grp} ? ' · <a href="/x/services/book/?g='.h(slugify($o->{grp})).'">'.h($o->{grp}).'</a>' : '').'</p>'
        .'<h1>'.h($o->{name}).'</h1><p class="booking-item__price">'.h(price_text($o)).($in_person ? ' · in person'.(@area ? ': '.h(join(', ',@area)) : '') : $mail ? ' · by mail: you send it, it comes back' : ' · done remotely').'</p>'
        .markdown_copy($o->{summary})
        .(length $problem ? '<p class="booking-problem" role="alert">'.h($problem).'</p>' : '').$form);
    end_page();
    return 1;
}
# Checks and keeps a booking. Returns what's wrong, or ends the request by
# sending the visitor on to the booking's page.
sub submit ($o) {
    my $origin=$ENV{HTTP_ORIGIN}//'';
    return 'This form has to be sent from this site.' if length $origin && !own_origin($origin);
    # Robots: the hidden field filled in, or sent faster than a person could.
    my $t=param('t',12);
    redirect('/x/services/book/') if length(param('website',200)) || ($t =~ /\A\d+\z/ && time-$t<3);
    my $visitor=sha256_hex(($ENV{REMOTE_ADDR}//'').'|'.int(time/3600).'|services');
    my $bdb=bookings_db();
    my $since=strftime('%Y-%m-%dT%H:%M:%SZ',gmtime(time-3600));
    return 'Too many bookings sent from here in the last hour. Try again later, or get in touch.' if $bdb->selectrow_array('SELECT count(*) FROM bookings WHERE visitor=? AND created_at>?',undef,$visitor,$since)>=5;
    # The offering's questions, answered and checked (the core's Questions.pm).
    my ($answers,$wrong)=BlowfishCMS::question_answers($o->{qs});
    return $wrong if length $wrong;
    my @got=@$answers;
    my @times;
    if ($o->{times}) {
        my $today=strftime('%Y-%m-%d',localtime);my $last=strftime('%Y-%m-%d',localtime(time+366*86400));
        for my $i (1..3) {
            my $d=param("d$i",10);my $p=param("p$i",10);$p='any' unless $parts{$p};
            next unless length $d;
            return 'Times: choose dates from the calendar.' unless $d =~ /\A\d{4}-\d\d-\d\d\z/;
            return 'Times: choose dates from today on.' if $d lt $today;
            return 'Times: choose dates within a year.' if $d gt $last;
            push @times,{date=>$d,part=>$p};
        }
        return 'Choose at least one time that suits you.' unless @times;
    }
    my ($street,$town)=('','');
    if ($o->{place} eq 'in_person' || $o->{place} eq 'mail') {
        $street=param('street',200);$town=param('town',80);
        return $o->{place} eq 'mail' ? 'Give the address to send it back to.' : 'Give the street address.' unless length $street;
        return $o->{place} eq 'mail' ? 'Give the town, state and postcode to send it back to.' : 'Give the town.' unless length $town;
        my @area=area_list($o);
        return 'Choose a town from the list: in person, that’s the area served.' if $o->{place} eq 'in_person' && @area && !grep {$_ eq $town} @area;
    }
    my $name=param('name',120);my $email=param('email',200);my $phone=param('phone',30);my $notes=param('notes',3000);$notes =~ s/\r\n?/\n/g;
    return 'Give your name.' unless length $name;
    return 'Give an email address that works: the booking’s details are sent there.' unless mail_address_ok($email);
    return 'Give a phone number.' if $o->{place} eq 'in_person' && !length $phone;
    return 'Phone: digits, spaces and + ( ) - only.' if length $phone && $phone !~ /\A[0-9+() .\-]{6,30}\z/;
    return 'Tick that you agree to the terms.' if length(addon_setting('services','terms','')) && param('agree',1) ne '1';
    my ($id,$k)=(random_id(),random_id());my $cur=currency();my $due=due_at_booking($o);
    $bdb->begin_work;
    attempt {
        $bdb->do('INSERT INTO bookings (id,k,offering,offering_name,pricing,amount,currency,place,name,email,phone,street,town,times,answers,notes,visitor,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',undef,
            $id,$k,$o->{slug},$o->{name},$o->{pricing},$o->{amount},$cur,$o->{place},$name,$email,$phone,$street,$town,json()->encode(\@times),json()->encode(\@got),$notes,$visitor,now(),now());
        $bdb->do('INSERT INTO payments (id,booking,amount,currency,purpose,status,created_at) VALUES (?,?,?,?,?,?,?)',undef,random_id(),$id,$due,$cur,$due==$o->{amount} ? 'price' : 'deposit','due',now()) if $due;
        $bdb->commit;1;
    } or do {my $e=$@;$bdb->rollback;warn "Services: booking not kept: $e";return 'The booking couldn’t be kept. Please try again in a minute.'};
    my $b=booking($id);
    email_owner("New booking: $b->{offering_name}, $b->{name}","A new booking request on ".site_name().":\n\n".booking_text($b)
        .($due ? "\nTo pay when booking: ".money($due,$cur)." (you’ll get an email once it’s paid).\n" : '')."\nSee it, and confirm a time, on the Bookings screen: ".admin_url($b)."\n",reply_to=>$b->{email});
    my $note=addon_setting('services','note','');
    email_customer($b,"Your booking request: $b->{offering_name}","Thank you: your request for $b->{offering_name} is in.\n\n".booking_text($b)
        ."\n".($due ? 'To book it, pay '.money($due,$cur).' from the link below (if you haven’t already).' : $o->{times} ? 'You’ll get an email when a time is confirmed.' : 'You’ll hear back soon.')."\n"
        .(length $note ? "\n$note\n" : ''));
    redirect("/x/services/booking/$id?k=$k");
}

# ---- A booking's own page ----
sub booking_page ($id) {
    my $b=booking($id);my $k=param('k',40);
    return 0 unless $b && length $k && eq_safe($k,$b->{k});
    my @pay=@{payments_of($b->{id})};
    my $state=$b->{status} eq 'cancelled' ? 'This booking was cancelled.'
        : $b->{status} eq 'done' ? 'Done. Thank you!'
        : length $b->{confirmed_time} ? "Booked for $b->{confirmed_time}."
        : 'Your request is in. You’ll get an email when '.(length(times_text($b)) ? 'a time is confirmed.' : 'it’s confirmed.');
    my $paid_now=param('paid',1) eq '1';
    my $html='<p class="booking-state">'.h($state).'</p>';
    $html.='<p class="booking-note" role="status">Thank you: your payment is being confirmed. This page says so once Stripe tells us.</p>' if $paid_now && grep {$_->{status} eq 'pending'} @pay;
    my @due=grep {$_->{status} eq 'due' || $_->{status} eq 'pending'} @pay;
    if (@due && $b->{status} ne 'cancelled') {
        $html.='<div class="booking-due">'.join('',map {'<p><strong>'.h(money($_->{amount},$_->{currency})).'</strong> due: '.h($purpose{$_->{purpose}}//'a payment').(length $_->{note} ? ': '.h($_->{note}) : '')
            .' '.cta_html('Pay '.money($_->{amount},$_->{currency}),"/x/services/pay/$_->{id}?k=$b->{k}",style=>'primary').'</p>'} @due).'<p class="optional">You pay on Stripe’s secure page; card details never reach this site.</p></div>';
    }
    my @done=grep {$_->{status} eq 'paid'} @pay;
    $html.='<p>Paid: '.join(', ',map {h(money($_->{amount},$_->{currency})).' ('.h($purpose{$_->{purpose}}//'a payment').')'} @done).'</p>' if @done;
    $html.='<h2>Your booking</h2><pre class="booking-summary">'.h(booking_text($b)).'</pre><p>Questions? Reply to the email you got, or <a href="/contact/">get in touch</a>.</p>';
    message_page($b->{offering_name},$html);
    return 1;
}

# ---- Payments (Stripe, through the core's Payments.pm, with this add-on's keys) ----
sub read_secret ($key) { return BlowfishCMS::stripe_secret('services',$key) }
sub stripe ($verb,$path,$pairs=[],%o) { return BlowfishCMS::stripe_request('services',$verb,$path,$pairs,%o) }
sub stripe_problem ($status,$reply) { return BlowfishCMS::stripe_problem($status,$reply) }
sub live_key ($key) { return BlowfishCMS::stripe_live($key) }
# /x/services/pay/PAYMENT?k=KEY: a payment that's due, started on Stripe's
# page (a new Checkout Session each time, so an old link still works).
sub pay ($pid) {
    my $bdb=bookings_db();
    my $p=$bdb->selectrow_hashref('SELECT * FROM payments WHERE id=?',undef,$pid);
    my $b=$p ? booking($p->{booking}) : undef;my $k=param('k',40);
    return 0 unless $b && length $k && eq_safe($k,$b->{k});
    my $page=booking_url($b);
    redirect($page) if $p->{status} eq 'paid' || $p->{status} eq 'cancelled' || $b->{status} eq 'cancelled';
    unless (length read_secret('stripe.key')) {message_page('Payment not open yet','<p>Online payment isn’t set up yet. You’ll be contacted about paying.</p><p><a href="'.h($page).'">Back to your booking</a></p>',503);return 1}
    my @pairs=(mode=>'payment',client_reference_id=>$p->{id},'metadata[payment]'=>$p->{id},'metadata[booking]'=>$b->{id},
        success_url=>booking_url($b,paid=>1),cancel_url=>$page,(mail_address_ok($b->{email}) ? (customer_email=>$b->{email}) : ()),
        'line_items[0][quantity]'=>1,'line_items[0][price_data][currency]'=>$p->{currency},'line_items[0][price_data][unit_amount]'=>$p->{amount},
        'line_items[0][price_data][product_data][name]'=>"$b->{offering_name}: ".($purpose{$p->{purpose}}//'a payment'));
    my ($status,$session)=stripe('POST','/v1/checkout/sessions',\@pairs);
    unless ($status==200 && ($session->{url}//'') =~ m{\Ahttps://}) {
        warn 'Services payment failed to start: '.stripe_problem($status,$session)."\n";
        message_page('Payment unavailable','<p>Payment couldn’t be started. Please try again in a minute.</p><p><a href="'.h($page).'">Back to your booking</a></p>',502);return 1;
    }
    $bdb->do("UPDATE payments SET status='pending',session=?,live=? WHERE id=? AND status<>'paid'",undef,$session->{id}//'',live_key(read_secret('stripe.key')),$p->{id});
    redirect($session->{url});
}
# Stripe calls this when a checkout finishes. The signature proves it's Stripe.
sub webhook {
    if ($BlowfishCMS::method ne 'POST') {header(405,'text/plain; charset=UTF-8');print 'Method Not Allowed';return}
    my ($event,$problem)=BlowfishCMS::stripe_webhook_event('services');
    unless ($event) {webhook_note(0,$problem);header(400,'text/plain; charset=UTF-8');print "Bad signature: $problem";return}
    my $bdb=bookings_db();
    my $new=$bdb->do('INSERT OR IGNORE INTO events (id,type,received_at) VALUES (?,?,?)',undef,$event->{id}//'',$event->{type}//'',now());
    if ($new>0) {
        my $s=$event->{data}{object}//{};my $pid=$s->{client_reference_id}//$s->{metadata}{payment}//'';
        my %to=('checkout.session.completed'=>(($s->{payment_status}//'') eq 'unpaid' ? 'pending' : 'paid'),
            'checkout.session.async_payment_succeeded'=>'paid','checkout.session.async_payment_failed'=>'due','checkout.session.expired'=>'due');
        if (my $st=$to{$event->{type}//''} and $pid =~ /\A[a-f0-9]{32}\z/) {
            # An expired or failed checkout leaves the payment due (its link still
            # works); a paid one is final, whichever of its checkouts was paid.
            my $n=$bdb->do("UPDATE payments SET status=?,paid_at=CASE WHEN ?='paid' THEN ? ELSE paid_at END,how=CASE WHEN ?='paid' THEN 'stripe' ELSE how END WHERE id=? AND status<>'paid' AND status<>'cancelled'",undef,
                $st,$st,now(),$st,$pid);
            attempt {payment_emails($pid)} if $n>0 && $st eq 'paid';
        }
    }
    webhook_note(1,$event->{type}//'');
    BlowfishCMS::json_response({received=>JSON::PP::true});
}
sub payment_emails ($pid) {
    my $p=bookings_db()->selectrow_hashref('SELECT * FROM payments WHERE id=?',undef,$pid) or return;
    my $b=booking($p->{booking}) or return;
    my $what=money($p->{amount},$p->{currency}).' for '.($purpose{$p->{purpose}}//'a payment');
    email_owner("Paid: $what, $b->{offering_name}, $b->{name}","$b->{name} paid $what ($b->{offering_name})".($p->{live} || $p->{how} ne 'stripe' ? '' : ' (test mode: no real money)').".\n\n".admin_url($b)."\n");
    email_customer($b,"Payment received: $b->{offering_name}","Thank you: $what is paid".($p->{how} eq 'stripe' ? ' (Stripe emails your receipt separately)' : '').'.');
}
sub webhook_note ($ok,$text) { attempt {bookings_db()->do('INSERT INTO webhook_log (id,ok,text,at) VALUES (1,?,?,?) ON CONFLICT(id) DO UPDATE SET ok=excluded.ok,text=excluded.text,at=excluded.at',undef,$ok ? 1 : 0,substr($text,0,300),now())} }
sub webhook_last { return attempt {bookings_db()->selectrow_hashref('SELECT * FROM webhook_log WHERE id=1')} }

# ---- Bookings screen (the services service, /admin/x/services/) ----------------------------------
sub service_admin ($rest) {
    return 0 unless $rest eq '';
    my $bdb=bookings_db();
    my $message=param('notice',2000);my $b=booking(param('b',32) || param('id',32));
    my $go=sub ($text,$id=undef) {redirect('/admin/x/services/?'.($id ? "b=$id&" : '').'notice='.CGI::escape(encode('UTF-8',$text)))};
    if ($BlowfishCMS::method eq 'POST') {
        attempt {
            my $action=param('action',30);
            # The Stripe panel's own actions (keys), done by the core.
            if (defined(my $done=BlowfishCMS::stripe_panel_action('services',$action))) {$go->($done)}
            $b or die "That booking no longer exists.\n";
            if ($action eq 'confirm') {
                my $when=param('when',120);my $other=param('when_other',120);$when=$other if $when eq 'other' || !length $when;
                die "Say when: choose one of their times, or write one in.\n" unless length $when;
                $bdb->do("UPDATE bookings SET status='confirmed',confirmed_time=?,updated_at=? WHERE id=?",undef,$when,now(),$b->{id});
                my $nb=booking($b->{id});
                email_customer($nb,"Confirmed: $nb->{offering_name}, $when","Your booking for $nb->{offering_name} is confirmed for $when.".($nb->{place} eq 'in_person' ? "\n\nAt: ".join(', ',grep {length} $nb->{street},$nb->{town}) : '')
                    .($nb->{place} eq 'mail' ? (length(addon_setting('services','mail_note','')) ? "\n\nSending it:\n".addon_setting('services','mail_note','') : '')."\n\nIt comes back to: ".join(', ',grep {length} $nb->{street},$nb->{town}) : '')) if param('tell',1) ne '0';
                $go->("Confirmed for $when.",$b->{id});
            }
            if ($action eq 'ask') {
                my $cur=$b->{currency};my $hours=param('hours',10);my $amount;
                if (length $hours) {
                    die "Hours: a number such as 1.5.\n" unless $hours =~ /\A\d{1,3}(?:[.,]\d{1,2})?\z/ && $hours>0;
                    die "Hours are for jobs priced by the hour.\n" unless $b->{pricing} eq 'hourly';
                    $amount=int($b->{amount}*($hours =~ tr/,/./r)+0.5);
                } else {$amount=parse_money(param('amount',20),'Amount',$cur)}
                # The down payment: its share of the estimate or price given.
                my $o=offering($b->{offering});my $pct=$o && $b->{pricing} ne 'fixed' ? $o->{down}//0 : 0;my $down_of='';
                if (param('down',1) eq '1' && $pct>0 && $pct<100) {$down_of=money($amount,$cur);$amount=int($amount*$pct/100+0.5)}
                die "Amount: Stripe needs at least 0.50.\n" if $amount<50;
                my $purpose=length $down_of ? 'deposit' : length $hours ? 'hours' : $b->{pricing} eq 'quote' ? 'quote' : $b->{pricing} eq 'fixed' && paid_total($b->{id}) ? 'balance' : $b->{pricing} eq 'fixed' ? 'price' : 'other';
                my $note=param('note',200);$note=(length $hours ? ($hours =~ tr/,/./r).' hours at '.money($b->{amount},$cur) : '').(length $note && length $hours ? '; ' : '').$note;
                $note="$pct% down payment of $down_of".(length $note ? "; $note" : '') if length $down_of;
                my $pid=random_id();
                $bdb->do('INSERT INTO payments (id,booking,amount,currency,purpose,note,status,created_at) VALUES (?,?,?,?,?,?,?,?)',undef,$pid,$b->{id},$amount,$cur,$purpose,$note,'due',now());
                email_customer($b,"Payment for $b->{offering_name}: ".money($amount,$cur),'Here’s the payment for '.$b->{offering_name}.': '.money($amount,$cur).(length $note ? " ($note)" : '').".\n\nPay it securely here: ".site_url()."/x/services/pay/$pid?k=$b->{k}");
                $go->('Asked for '.money($amount,$cur).($b->{email} ? ", emailed to $b->{email}" : '').'.',$b->{id});
            }
            if ($action eq 'paid_cash') {
                my $n=$bdb->do("UPDATE payments SET status='paid',how='in person',paid_at=? WHERE id=? AND booking=? AND status IN ('due','pending')",undef,now(),param('payment',32),$b->{id});
                die "That payment isn’t waiting to be paid.\n" unless $n>0;
                attempt {payment_emails(param('payment',32))};
                $go->('Marked paid.',$b->{id});
            }
            if ($action eq 'payment_cancel') {
                my $n=$bdb->do("UPDATE payments SET status='cancelled' WHERE id=? AND booking=? AND status IN ('due','pending')",undef,param('payment',32),$b->{id});
                die "That payment isn’t waiting to be paid.\n" unless $n>0;
                $go->('That payment is no longer asked for; its link stops working.',$b->{id});
            }
            if ($action eq 'done' || $action eq 'reopen' || $action eq 'cancel') {
                my $st={done=>'done',reopen=>(length $b->{confirmed_time} ? 'confirmed' : 'requested'),cancel=>'cancelled'}->{$action};
                $bdb->do('UPDATE bookings SET status=?,updated_at=? WHERE id=?',undef,$st,now(),$b->{id});
                $bdb->do("UPDATE payments SET status='cancelled' WHERE booking=? AND status IN ('due','pending')",undef,$b->{id}) if $st eq 'cancelled';
                email_customer($b,"Cancelled: $b->{offering_name}","Your booking for $b->{offering_name} is cancelled.".(paid_total($b->{id}) ? ' Anything you paid will be refunded.' : '')) if $st eq 'cancelled' && param('tell',1) ne '0';
                $go->({done=>'Marked done.',reopen=>'Open again.',cancel=>'Cancelled.'}->{$action},$b->{id});
            }
            if ($action eq 'delete') {
                $bdb->do('DELETE FROM payments WHERE booking=?',undef,$b->{id});
                $bdb->do('DELETE FROM bookings WHERE id=?',undef,$b->{id});
                $go->("Deleted $b->{name}’s booking.");
            }
            die "Choose an action.\n";
        } or $message=failed_action($@);
    }
    my $css='<link rel="stylesheet" href="/addons/services/services.css?v=2.0.0">';
    if ($b) {
        admin_page('Bookings',section=>'x-services-service',notice=>$message,intro=>'<a href="/admin/x/services/">All bookings</a> · '.h($b->{offering_name}).', '.h($status{$b->{status}}//$b->{status}).'.');
        print $css;
        my @pay=@{payments_of($b->{id})};my $cur=$b->{currency};
        window(lc($b->{name}).' · '.lc($b->{offering_name}),'<dl class="booking-dl"><dt>Asked for</dt><dd>'.h($b->{offering_name}).' · '.h(price_text($b)).'</dd>'
            .'<dt>Name</dt><dd>'.h($b->{name}).'</dd><dt>Email</dt><dd><a href="mailto:'.h($b->{email}).'">'.h($b->{email}).'</a></dd>'
            .(length $b->{phone} ? '<dt>Phone</dt><dd><a href="tel:'.h($b->{phone} =~ s/[^0-9+]//gr).'">'.h($b->{phone}).'</a></dd>' : '')
            .($b->{place} eq 'in_person' ? '<dt>Address</dt><dd>'.h(join(', ',grep {length} $b->{street},$b->{town})).'</dd>' : $b->{place} eq 'mail' ? '<dt>By mail: send it back to</dt><dd>'.h(join(', ',grep {length} $b->{street},$b->{town})).'</dd>' : '<dt>Where</dt><dd>remotely</dd>')
            .(length $b->{confirmed_time} ? '<dt>Confirmed for</dt><dd>'.h($b->{confirmed_time}).'</dd>' : '')
            .(length(times_text($b)) ? '<dt>Times that suit</dt><dd>'.(h(times_text($b)) =~ s/\n/<br>/gr).'</dd>' : '')
            .join('',map {'<dt>'.h($_->{label}).'</dt><dd>'.(length $_->{value} ? h($_->{value}) =~ s/\n/<br>/gr : '<span class="media-label">no answer</span>').'</dd>'} @{decoded($b->{answers})})
            .(length $b->{notes} ? '<dt>Anything else</dt><dd>'.(h($b->{notes}) =~ s/\n/<br>/gr).'</dd>' : '')
            .'<dt>Sent</dt><dd>'.h($b->{created_at} =~ s/T/ /r =~ s/:\d\dZ\z/ UTC/r).'</dd></dl>');
        unless ($b->{status} eq 'cancelled' || $b->{status} eq 'done') {
            my @t=@{decoded($b->{times})};
            window('confirm a time','<form method="post" action="/admin/x/services/" class="admin-form">'.fields('confirm','x-services',$b->{id})
                .(@t ? '<fieldset><legend>When</legend>'.join('',map {my $w=pretty_date($_->{date}).', '.lc($parts{$_->{part}}//'any time');'<label class="checkbox-label"><input type="radio" name="when" value="'.h($w).'"> '.h($w).'</label>'} @t)
                    .'<label class="checkbox-label"><input type="radio" name="when" value="other"'.(@t ? '' : ' checked').'> another time:</label></fieldset>' : '<input type="hidden" name="when" value="other">')
                .'<label>'.(@t ? 'Another time, or the exact time' : 'When').'<input name="when_other" maxlength="120" placeholder="Tuesday 3 December, 10am"></label>'
                .'<label class="checkbox-label"><input type="checkbox" name="tell" value="1" checked>Email it to them<input type="hidden" name="tell" value="0"></label>'
                .'<button class="buttonlike is-primary" type="submit">confirm</button></form>');
        }
        my $rows=@pay ? '<table class="seo-table booking-payments"><thead><tr><th>Amount</th><th>For</th><th>Status</th><th></th></tr></thead><tbody>'.join('',map {my $p=$_;
            '<tr><td>'.h(money($p->{amount},$p->{currency})).'</td><td>'.h($purpose{$p->{purpose}}//'').(length $p->{note} ? '<br><span class="media-label">'.h($p->{note}).'</span>' : '').'</td>'
            .'<td>'.h($p->{status} eq 'paid' ? 'paid'.($p->{how} eq 'in person' ? ' in person' : $p->{live} ? '' : ' (test)').' '.substr($p->{paid_at}//'',0,10) : $p->{status} eq 'pending' ? 'at Stripe' : $p->{status}).'</td>'
            .'<td>'.($p->{status} =~ /\A(?:due|pending)\z/ ? '<form method="post" action="/admin/x/services/">'.fields('paid_cash','x-services',$b->{id}).hidden(payment=>$p->{id}).'<button class="text-button">paid in person</button></form>'
                .'<form method="post" action="/admin/x/services/">'.fields('payment_cancel','x-services',$b->{id}).hidden(payment=>$p->{id}).'<button class="text-button">no longer due</button></form>' : '').'</td></tr>'} @pay).'</tbody></table>'
            : '<p class="empty-media">Nothing asked for yet.</p>';
        my $ask=$b->{status} eq 'cancelled' ? '' : '<form method="post" action="/admin/x/services/" class="admin-form"><h3>Ask for a payment</h3>'.fields('ask','x-services',$b->{id}).'<div class="theme-editor__grid">'
            .($b->{pricing} eq 'hourly' ? '<label>Hours worked<input name="hours" maxlength="10" inputmode="decimal" placeholder="1.5"><span class="optional">at '.h(money($b->{amount},$cur)).' an hour; or leave empty and give an amount</span></label>' : '')
            .'<label>Amount ('.uc($cur).')<input name="amount" maxlength="20" inputmode="decimal" placeholder="'.h($b->{pricing} eq 'fixed' ? money_input($b->{amount}-paid_total($b->{id}),$cur) : '').'"></label>'
            .'<label>What it’s for<input name="note" maxlength="200" placeholder="such as “new SSD and fitting”"><span class="optional">optional; shown to them</span></label></div>'
            .(do {my $o=offering($b->{offering});my $pct=$o && $b->{pricing} ne 'fixed' ? $o->{down}//0 : 0;my $asked=grep {$_->{purpose} eq 'deposit' && $_->{status} ne 'cancelled'} @pay;
                $pct>0 && $pct<100 && !$asked ? switch_field('down',"Ask for the $pct% down payment of it",1,hint=>"Give the whole estimate or price as the amount; they’re asked for $pct% of it now, the rest after the job.") : ''})
            .'<p class="media-label">They get an email with a link to pay on Stripe. Paid in cash or by card in person? Ask for it here, then mark it “paid in person”.</p><button class="buttonlike" type="submit">ask for payment</button></form>';
        window('payments',$rows.$ask);
        my $act=sub ($a,$label,$confirm='',$tell=0) {'<form method="post" action="/admin/x/services/" class="'.($confirm ? 'delete-form' : 'inline-form').'"'.($confirm ? ' data-confirm="'.h($confirm).'"' : '').'>'.fields($a,'x-services',$b->{id}).($tell ? hidden(tell=>1) : '').'<button class="buttonlike'.($a eq 'delete' || $a eq 'cancel' ? ' danger' : '').'">'.h($label).'</button></form>'};
        window('the booking',join(' ',$b->{status} =~ /\A(?:requested|confirmed)\z/ ? ($act->('done','mark done'),$act->('cancel','cancel it (and email them)','Cancel this booking? They get an email, and anything still due is no longer asked for.',1)) : $act->('reopen','open it again'),
            $act->('delete','delete it','Delete this booking and its payments for good? Use this to remove someone’s details.')).'<p class="media-label">Their page: <a href="'.h(booking_url($b)).'" target="_blank" rel="noopener">'.h(booking_url($b) =~ s/\?k=.*//r).'</a> (its link, with its key, is in their emails). Refunds are made in the Stripe Dashboard.</p>');
        end_page();return 1;
    }
    admin_page('Bookings',section=>'x-services-service',notice=>$message,intro=>'What people booked. Open one to confirm a time, ask for payment and mark it done.');
    print $css;
    my $show=param('show',10);$show='open' unless $show =~ /\A(?:open|done|cancelled|all)\z/;
    my $where={open=>"status IN ('requested','confirmed')",done=>"status='done'",cancelled=>"status='cancelled'",all=>'1=1'}->{$show};
    my $list=$bdb->selectall_arrayref("SELECT b.*,(SELECT coalesce(sum(amount),0) FROM payments p WHERE p.booking=b.id AND p.status IN ('due','pending')) AS owed FROM bookings b WHERE $where ORDER BY created_at DESC LIMIT 300",{Slice=>{}});
    my $tabs='<p class="store-filter">'.join(' · ',map {$_->[0] eq $show ? '<strong>'.$_->[1].'</strong>' : '<a href="/admin/x/services/?show='.$_->[0].'">'.$_->[1].'</a>'} [open=>'open'],[done=>'done'],[cancelled=>'cancelled'],[all=>'everything']).'</p>';
    window('bookings',$tabs.(@$list ? '<table class="seo-table booking-table"><thead><tr><th>Sent</th><th>What</th><th>Who</th><th>When</th><th>Status</th></tr></thead><tbody>'.join('',map {
        '<tr><td>'.h(substr($_->{created_at},0,10)).'</td><td><a href="/admin/x/services/?b='.h($_->{id}).'">'.h($_->{offering_name}).'</a></td><td>'.h($_->{name}).($_->{place} eq 'in_person' ? '<br><span class="media-label">'.h($_->{town}).'</span>' : $_->{place} eq 'mail' ? '<br><span class="media-label">by mail</span>' : '').'</td>'
        .'<td>'.(length $_->{confirmed_time} ? h($_->{confirmed_time}) : '<span class="media-label">'.h(join(' · ',map {pretty_date($_->{date})} @{decoded($_->{times})})).'</span>').'</td>'
        .'<td>'.h($status{$_->{status}}//$_->{status}).($_->{owed} ? '<br><span class="media-label">'.h(money($_->{owed},$_->{currency})).' due</span>' : '').'</td></tr>'} @$list).'</tbody></table>' : '<p class="empty-media">No bookings here.</p>'));
    window('stripe',BlowfishCMS::stripe_panel_html('services','/admin/x/services/',webhook=>'/x/services/webhook',last=>scalar(webhook_last()),unset=>'bookings work, but nothing can be paid online'));
    end_page();
    return 1;
}
# A date as people say it: "Tue 3 Dec 2026".
sub pretty_date ($d) { my ($y,$m,$day)=$d =~ /\A(\d{4})-(\d\d)-(\d\d)\z/ or return $d;return strftime('%a %e %b %Y',0,0,12,$day,$m-1,$y-1900) =~ s/  / /r }

1;