<?php
require_once __DIR__ . '/../Core.php';

class UserIntegrationProfile extends Model
{
    private array $encryptedFields = ['twilio_token', 'smtp_password'];

    public function findByUserId(int $userId): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM user_integration_profiles WHERE user_id = ? LIMIT 1');
        $stmt->execute([$userId]);
        $row = $stmt->fetch() ?: null;
        if (!$row) {
            return null;
        }
        foreach ($this->encryptedFields as $field) {
            if (array_key_exists($field, $row)) {
                $row[$field] = decrypt_value($row[$field]);
            }
        }
        return $row;
    }

    public function saveForUser(int $userId, array $data): bool
    {
        $existing = $this->findByUserId($userId);
        $payload = [
            'preferred_channel' => $data['preferred_channel'] ?? 'email',
            'use_personal_twilio' => !empty($data['use_personal_twilio']) ? 1 : 0,
            'twilio_sid' => trim((string)($data['twilio_sid'] ?? '')),
            'twilio_token' => trim((string)($data['twilio_token'] ?? '')),
            'twilio_from_number' => trim((string)($data['twilio_from_number'] ?? '')),
            'use_personal_mail' => !empty($data['use_personal_mail']) ? 1 : 0,
            'mail_from_name' => trim((string)($data['mail_from_name'] ?? '')),
            'mail_from_email' => trim((string)($data['mail_from_email'] ?? '')),
            'smtp_enabled' => !empty($data['smtp_enabled']) ? 1 : 0,
            'smtp_host' => trim((string)($data['smtp_host'] ?? '')),
            'smtp_port' => (int)($data['smtp_port'] ?? 587),
            'smtp_username' => trim((string)($data['smtp_username'] ?? '')),
            'smtp_password' => trim((string)($data['smtp_password'] ?? '')),
            'smtp_secure' => trim((string)($data['smtp_secure'] ?? 'tls')) ?: 'tls',
            'reply_to_email' => trim((string)($data['reply_to_email'] ?? '')),
            'default_sms_footer' => trim((string)($data['default_sms_footer'] ?? '')),
            'default_email_footer' => trim((string)($data['default_email_footer'] ?? '')),
            'signature_name' => trim((string)($data['signature_name'] ?? '')),
        ];
        foreach ($this->encryptedFields as $field) {
            $payload[$field] = (string)encrypt_value((string)$payload[$field]);
        }
        if ($existing) {
            $stmt = $this->db->prepare('UPDATE user_integration_profiles SET preferred_channel=?, use_personal_twilio=?, twilio_sid=?, twilio_token=?, twilio_from_number=?, use_personal_mail=?, mail_from_name=?, mail_from_email=?, smtp_enabled=?, smtp_host=?, smtp_port=?, smtp_username=?, smtp_password=?, smtp_secure=?, reply_to_email=?, default_sms_footer=?, default_email_footer=?, signature_name=?, updated_at=NOW() WHERE user_id=?');
            return $stmt->execute(array_merge(array_values($payload), [$userId]));
        }
        $stmt = $this->db->prepare('INSERT INTO user_integration_profiles (preferred_channel, use_personal_twilio, twilio_sid, twilio_token, twilio_from_number, use_personal_mail, mail_from_name, mail_from_email, smtp_enabled, smtp_host, smtp_port, smtp_username, smtp_password, smtp_secure, reply_to_email, default_sms_footer, default_email_footer, signature_name, user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
        return $stmt->execute(array_merge(array_values($payload), [$userId]));
    }
}
