<?php

namespace App\Models;

use App\Core\Database;

/**
 * DriverReminder Model
 * Manages driver registration reminders for follow-up notifications.
 */
class DriverReminder extends BaseModel
{
    protected static string $table = 'driver_registration_reminders';

    /**
     * Find active reminder by company and contact phone
     */
    public static function findActive(int $companyId, string $phone): ?array
    {
        self::ensureTableExists();
        return Database::selectOne(
            "SELECT * FROM " . static::$table . " WHERE company_id = ? AND phone = ? AND status = 'pending' LIMIT 1",
            [$companyId, $phone]
        );
    }

    /**
     * Save or update driver reminder state
     */
    public static function saveReminder(array $data): string
    {
        self::ensureTableExists();

        $existing = Database::selectOne(
            "SELECT id FROM " . static::$table . " WHERE company_id = ? AND phone = ? AND status = 'pending' LIMIT 1",
            [$data['company_id'], $data['phone']]
        );

        if ($existing) {
            self::update($existing['id'], $data);
            return $existing['id'];
        } else {
            return self::create($data);
        }
    }

    /**
     * Ensure the driver_registration_reminders table exists dynamically
     */
    public static function ensureTableExists(): void
    {
        static $checked = false;
        if ($checked) return;

        try {
            Database::execute("
                CREATE TABLE IF NOT EXISTS `driver_registration_reminders` (
                    `id` INT AUTO_INCREMENT PRIMARY KEY,
                    `company_id` INT NOT NULL,
                    `phone` VARCHAR(50) NOT NULL,
                    `scheduled_at` DATETIME NOT NULL,
                    `postpone_count` INT DEFAULT 0,
                    `status` VARCHAR(20) DEFAULT 'pending',
                    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
            ");
            $checked = true;
        } catch (\Exception $e) {
            error_log("Failed to ensure driver_registration_reminders table: " . $e->getMessage());
        }
    }
}
