<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

/**
 * Add SMS as a parallel reminder channel.
 *
 *  - clc_reminder_settings + sms_enabled toggle (per business)
 *  - clc_reminder_templates: extend the `type` enum with 'sms_due' / 'sms_overdue'
 *  - Seed a system-default SMS template for each new type (no rows touch
 *    existing customised email templates).
 *
 * SMS goes out via the existing core SMS engine — `Util::sendSms($data)`
 * with the business's `sms_settings`. No new gateway code in the vet module.
 */
class ClcAddSmsToVetReminders extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_reminder_settings')
            && !Schema::hasColumn('clc_reminder_settings', 'sms_enabled'))
        {
            Schema::table('clc_reminder_settings', function (Blueprint $table) {
                $table->boolean('sms_enabled')->default(false)->after('email_enabled');
            });
        }

        if (Schema::hasTable('clc_reminder_templates')) {
            // Extend enum — done via raw ALTER because Doctrine's enum support
            // is limited. Order is: email_due, email_overdue, wa_due, wa_overdue,
            // sms_due, sms_overdue. We only add the two new values, no data loss.
            $driver = Schema::getConnection()->getDriverName();
            if ($driver === 'mysql' || $driver === 'mariadb') {
                DB::statement(
                    "ALTER TABLE clc_reminder_templates MODIFY COLUMN type " .
                    "ENUM('email_due','email_overdue','wa_due','wa_overdue','sms_due','sms_overdue') NOT NULL"
                );
            }

            $now = now();

            $defaults = [
                [
                    'type'    => 'sms_due',
                    'name'    => 'SMS — Vaccine due',
                    'subject' => null,
                    'body'    => 'Hi {{owner_name}}, this is a reminder that {{pet_name}}\'s {{vaccine_name}} '
                               . 'is due on {{due_date}}. Please book at {{clinic_name}} on {{clinic_phone}}.',
                ],
                [
                    'type'    => 'sms_overdue',
                    'name'    => 'SMS — Vaccine overdue',
                    'subject' => null,
                    'body'    => 'Hi {{owner_name}}, {{pet_name}}\'s {{vaccine_name}} is now {{days_until_due}}. '
                               . 'Please call {{clinic_name}} on {{clinic_phone}} to schedule.',
                ],
            ];

            foreach ($defaults as $d) {
                $exists = DB::table('clc_reminder_templates')
                    ->whereNull('business_id')
                    ->where('type', $d['type'])
                    ->where('is_system_default', true)
                    ->exists();
                if ($exists) continue;

                DB::table('clc_reminder_templates')->insert([
                    'business_id'       => null,
                    'type'              => $d['type'],
                    'name'              => $d['name'],
                    'subject'           => $d['subject'],
                    'body'              => $d['body'],
                    'is_active'         => true,
                    'is_system_default' => true,
                    'created_at'        => $now,
                    'updated_at'        => $now,
                ]);
            }
        }
    }

    public function down()
    {
        if (Schema::hasTable('clc_reminder_settings')
            && Schema::hasColumn('clc_reminder_settings', 'sms_enabled'))
        {
            Schema::table('clc_reminder_settings', function (Blueprint $table) {
                $table->dropColumn('sms_enabled');
            });
        }

        if (Schema::hasTable('clc_reminder_templates')) {
            DB::table('clc_reminder_templates')
                ->whereNull('business_id')
                ->whereIn('type', ['sms_due', 'sms_overdue'])
                ->where('is_system_default', true)
                ->delete();

            $driver = Schema::getConnection()->getDriverName();
            if ($driver === 'mysql' || $driver === 'mariadb') {
                DB::statement(
                    "ALTER TABLE clc_reminder_templates MODIFY COLUMN type " .
                    "ENUM('email_due','email_overdue','wa_due','wa_overdue') NOT NULL"
                );
            }
        }
    }
}
