<?php

/**
 * NotificationSubscription Model
 * Handles push notification subscription data
 */
class NotificationSubscription {
    
    private $db;
    private $table = 'notification_subscriptions';
    
    public function __construct() {
        $this->db = Database::getInstance()->getConnection();
    }
    
    /**
     * Create or update a subscription
     */
    public function createOrUpdate($userId, $endpoint, $p256dhKey, $authKey) {
        try {
            // Check if subscription already exists for this user and endpoint
            $stmt = $this->db->prepare("
                SELECT id FROM {$this->table} 
                WHERE user_id = ? AND endpoint = ?
            ");
            $stmt->execute([$userId, $endpoint]);
            $existing = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($existing) {
                // Update existing subscription
                $stmt = $this->db->prepare("
                    UPDATE {$this->table} 
                    SET p256dh_key = ?, auth_key = ?
                    WHERE id = ?
                ");
                return $stmt->execute([$p256dhKey, $authKey, $existing['id']]);
            } else {
                // Create new subscription
                $stmt = $this->db->prepare("
                    INSERT INTO {$this->table} (user_id, endpoint, p256dh_key, auth_key)
                    VALUES (?, ?, ?, ?)
                ");
                return $stmt->execute([$userId, $endpoint, $p256dhKey, $authKey]);
            }
        } catch (PDOException $e) {
            logError('Failed to create/update notification subscription: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get all subscriptions for a user
     */
    public function getByUser($userId) {
        try {
            $stmt = $this->db->prepare("
                SELECT * FROM {$this->table}
                WHERE user_id = ?
                ORDER BY created_at DESC
            ");
            $stmt->execute([$userId]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            logError('Failed to get user subscriptions: ' . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Get all active subscriptions
     */
    public function getAllActive() {
        try {
            $stmt = $this->db->prepare("
                SELECT ns.*, u.username, u.email 
                FROM {$this->table} ns
                INNER JOIN users u ON ns.user_id = u.id
                WHERE u.is_active = 1
                ORDER BY ns.created_at DESC
            ");
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            logError('Failed to get all active subscriptions: ' . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Delete a subscription
     */
    public function delete($userId, $endpoint) {
        try {
            $stmt = $this->db->prepare("
                DELETE FROM {$this->table}
                WHERE user_id = ? AND endpoint = ?
            ");
            return $stmt->execute([$userId, $endpoint]);
        } catch (PDOException $e) {
            logError('Failed to delete subscription: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Delete all subscriptions for a user
     */
    public function deleteByUser($userId) {
        try {
            $stmt = $this->db->prepare("
                DELETE FROM {$this->table}
                WHERE user_id = ?
            ");
            return $stmt->execute([$userId]);
        } catch (PDOException $e) {
            logError('Failed to delete user subscriptions: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get subscription by ID
     */
    public function findById($id) {
        try {
            $stmt = $this->db->prepare("
                SELECT * FROM {$this->table}
                WHERE id = ?
            ");
            $stmt->execute([$id]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            logError('Failed to find subscription: ' . $e->getMessage());
            return null;
        }
    }
    
    /**
     * Check if user has any active subscriptions
     */
    public function hasActiveSubscription($userId) {
        try {
            $stmt = $this->db->prepare("
                SELECT COUNT(*) as count FROM {$this->table}
                WHERE user_id = ?
            ");
            $stmt->execute([$userId]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return $result['count'] > 0;
        } catch (PDOException $e) {
            logError('Failed to check active subscription: ' . $e->getMessage());
            return false;
        }
    }
}
