<?php

namespace App\Models;

use App\Core\Security;

use App\Core\Database;

/**
 * WhatsAppSession Model
 * Handles the whatsapp_sessions table with encryption for phone and QR code.
 */
class WhatsAppSession extends BaseModel
{
    protected static string $table = 'whatsapp_sessions';

    /**
     * Get the session for a specific company
     */
    public static function findByCompany(int $companyId)
    {
        $session = Database::selectOne(
            "SELECT * FROM " . static::$table . " WHERE company_id = ? LIMIT 1",
            [$companyId]
        );

        if ($session) {
            $session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
            $session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
        }

        return $session;
    }

    /**
     * Find secure session by ID
     */
    public static function findSecure(int $id)
    {
        $session = Database::selectOne(
            "SELECT * FROM " . static::$table . " WHERE id = ? LIMIT 1",
            [$id]
        );

        if ($session) {
            $session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
            $session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
        }

        return $session;
    }

    /**
     * Get all WhatsApp sessions for a company
     */
    public static function findAllByCompany(int $companyId): array
    {
        $sessions = Database::select(
            "SELECT * FROM " . static::$table . " WHERE company_id = ? ORDER BY id ASC",
            [$companyId]
        );

        foreach ($sessions as &$session) {
            $session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
            $session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
        }

        return $sessions;
    }

    /**
     * Get a session by session_key (used by webhooks)
     */
    public static function findBySessionKey(string $sessionKey)
    {
        $session = Database::selectOne(
            "SELECT * FROM " . static::$table . " WHERE session_key = ? LIMIT 1",
            [$sessionKey]
        );

        if ($session) {
            $session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
            $session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
        }

        return $session;
    }

    /**
     * Find session by phone number (useful to prevent duplicates across companies)
     */
    public static function findByPhone(string $phone)
    {
        $phoneHash = Security::blindIndex($phone);
        $session = Database::selectOne(
            "SELECT * FROM " . static::$table . " WHERE phone_hash = ? LIMIT 1",
            [$phoneHash]
        );

        if ($session) {
            $session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
            $session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
        }

        return $session;
    }

    /**
     * Create or retrieve a new session for a company
     */
    public static function findOrCreate(int $companyId, string $name = 'Main WhatsApp')
    {
        $session = static::findByCompany($companyId);
        if ($session) {
            return $session;
        }

        $sessionKey = 'cmp_' . $companyId . '_' . bin2hex(random_bytes(4));

        $id = static::create([
            'company_id' => $companyId,
            'name' => $name,
            'session_key' => $sessionKey,
            'status' => 'disconnected'
        ]);

        return static::findByCompany($companyId);
    }

    /**
     * Update session state securely
     */
    public static function updateState(int $id, array $data)
    {
        if (isset($data['phone'])) {
            $data['phone_hash'] = Security::blindIndex($data['phone']);
            $data['phone'] = Security::encrypt($data['phone']);
        }

        if (isset($data['qr_code'])) {
            $data['qr_code'] = Security::encrypt($data['qr_code']);
        }

        return static::update($id, $data);
    }
}
