<?php

/**
 * Migration 0058 — recurring bookings (series)
 *
 * A cleaner's money is in the weekly repeat, not the one-off visit, which is
 * why BookingKoala and Jobber win that trade. This adds the missing half.
 *
 * Deliberately NOT built on inst_instinctor_subscriptions: that model is
 * BILLING (Stripe/Authorize periods, card on file, webhooks) and knows nothing
 * about start_time, staff, slots or availability. It supplies the recurrence
 * vocabulary (period + interval_count) and, when the owner wants to charge on a
 * cycle, a subscription_id can be attached here. Scheduling stays with the
 * booking engine, which owns buffers, blocked ranges and staff hours.
 *
 * A series is a RULE. Real rows in instinctor_bookings remain the source of
 * truth for what is on the calendar, each stamped with series_id, so every
 * existing query, availability check, reminder and deposit path keeps working
 * untouched and a single occurrence can be moved or cancelled on its own.
 */

if ( ! defined( 'ABSPATH' ) ) exit;

return [
    'description' => 'Create inst_instinctor_booking_series + link bookings to a series',

    'up' => [
        "CREATE TABLE IF NOT EXISTS {prefix}instinctor_booking_series (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            owner_id int DEFAULT NULL,
            service_id bigint(20) unsigned NOT NULL,
            staff_id bigint(20) unsigned NOT NULL DEFAULT 0,
            customer_id bigint(20) unsigned NOT NULL DEFAULT 0,
            subscription_id bigint(20) unsigned DEFAULT NULL,
            period varchar(20) NOT NULL DEFAULT 'week',
            interval_count int NOT NULL DEFAULT 1,
            weekday tinyint NOT NULL DEFAULT 1,
            start_time_local time NOT NULL,
            duration_minutes int NOT NULL DEFAULT 60,
            timezone varchar(100) NOT NULL DEFAULT '',
            starts_on date NOT NULL,
            ends_on date DEFAULT NULL,
            occurrences int DEFAULT NULL,
            generated_through date DEFAULT NULL,
            status varchar(20) NOT NULL DEFAULT 'active',
            customer_note text,
            meta longtext,
            created_at datetime NOT NULL,
            updated_at datetime DEFAULT NULL,
            PRIMARY KEY (id),
            KEY owner_id (owner_id),
            KEY service_id (service_id),
            KEY status_generated (status, generated_through)
        ) {charset}",

        "ALTER TABLE {prefix}instinctor_bookings
            ADD COLUMN series_id bigint(20) unsigned DEFAULT NULL",

        "ALTER TABLE {prefix}instinctor_bookings
            ADD KEY series_id (series_id)",
    ],
];
