<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ScheduledNotification extends Model
{
    protected $table = 'scheduled_notifications';

    protected $fillable = [
        'caso_id',
        'tipo',
        'programada_para',
        'enviada_en',
        'activa',
        'data',
        'intentos',
    ];

    protected $casts = [
        'programada_para' => 'datetime',
        'enviada_en' => 'datetime',
        'activa' => 'boolean',
        'data' => 'array',
    ];

    public function caso(): BelongsTo
    {
        return $this->belongsTo(Caso::class);
    }

    /**
     * Schedule the IMPAR quotation reminder chain (M6):
     * - First reminder at 4h30m
     * - Second reminder at 5h
     * - Then every 30min until response
     */
    public static function scheduleImparReminders(int $casoId, array $extraData = []): void
    {
        $baseTime = now();
        $reminders = [
            ['offset' => 270, 'tipo' => 'impar_reminder_4h30'],   // 4h30m
            ['offset' => 300, 'tipo' => 'impar_reminder_5h'],      // 5h
            ['offset' => 330, 'tipo' => 'impar_reminder_5h30'],    // 5h30m
            ['offset' => 360, 'tipo' => 'impar_reminder_6h'],      // 6h
            ['offset' => 390, 'tipo' => 'impar_reminder_6h30'],    // 6h30m
            ['offset' => 420, 'tipo' => 'impar_reminder_7h'],      // 7h
        ];

        foreach ($reminders as $reminder) {
            self::create([
                'caso_id' => $casoId,
                'tipo' => $reminder['tipo'],
                'programada_para' => $baseTime->copy()->addMinutes($reminder['offset']),
                'activa' => true,
                'data' => $extraData,
            ]);
        }
    }

    /**
     * Schedule the delivery reminder for the day before (M6):
     * Proveedor must confirm delivery the day before the promised date.
     */
    public static function scheduleEntregaReminder(int $casoId, string $fechaEntrega, array $extraData = []): void
    {
        $diaAnterior = Carbon::parse($fechaEntrega)->subDay()->setHour(9)->setMinute(0);

        self::create([
            'caso_id' => $casoId,
            'tipo' => 'entrega_reminder',
            'programada_para' => $diaAnterior,
            'activa' => true,
            'data' => $extraData,
        ]);
    }

    /**
     * Cancel all pending reminders for a case of a given type prefix.
     */
    public static function cancelReminders(int $casoId, string $tipoPrefix = 'impar_reminder'): void
    {
        self::where('caso_id', $casoId)
            ->where('tipo', 'like', $tipoPrefix.'%')
            ->where('activa', true)
            ->whereNull('enviada_en')
            ->update(['activa' => false]);
    }
}
