<?php

/**
 * API Controller
 * Handles RESTful API endpoints for PWA
 */
class ApiController {
    
    private $notificationModel;
    
    public function __construct() {
        $this->notificationModel = new NotificationSubscription();
    }
    
    /**
     * Subscribe to push notifications
     * POST /api/notifications/subscribe
     */
    public function subscribeNotifications() {
        // Require authentication
        if (!isAuthenticated()) {
            jsonError('Authentication required', 'AUTH_ERROR', 401);
        }
        
        // Get JSON input
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            jsonError('Invalid JSON input', 'VALIDATION_ERROR', 400);
        }
        
        // Validate required fields
        if (empty($input['endpoint'])) {
            jsonError('Endpoint is required', 'VALIDATION_ERROR', 400);
        }
        
        if (empty($input['keys']) || empty($input['keys']['p256dh']) || empty($input['keys']['auth'])) {
            jsonError('Encryption keys are required', 'VALIDATION_ERROR', 400);
        }
        
        $userId = getCurrentUserId();
        $endpoint = $input['endpoint'];
        $p256dhKey = $input['keys']['p256dh'];
        $authKey = $input['keys']['auth'];
        
        // Create or update subscription
        $result = $this->notificationModel->createOrUpdate($userId, $endpoint, $p256dhKey, $authKey);
        
        if ($result) {
            jsonSuccess([
                'subscribed' => true,
                'user_id' => $userId
            ], 'Successfully subscribed to notifications');
        } else {
            jsonError('Failed to save subscription', 'DATABASE_ERROR', 500);
        }
    }
    
    /**
     * Unsubscribe from push notifications
     * POST /api/notifications/unsubscribe
     */
    public function unsubscribeNotifications() {
        // Require authentication
        if (!isAuthenticated()) {
            jsonError('Authentication required', 'AUTH_ERROR', 401);
        }
        
        // Get JSON input
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input || empty($input['endpoint'])) {
            jsonError('Endpoint is required', 'VALIDATION_ERROR', 400);
        }
        
        $userId = getCurrentUserId();
        $endpoint = $input['endpoint'];
        
        // Delete subscription
        $result = $this->notificationModel->delete($userId, $endpoint);
        
        if ($result) {
            jsonSuccess([
                'unsubscribed' => true,
                'user_id' => $userId
            ], 'Successfully unsubscribed from notifications');
        } else {
            jsonError('Failed to remove subscription', 'DATABASE_ERROR', 500);
        }
    }
    
    /**
     * Get subscription status
     * GET /api/notifications/status
     */
    public function notificationStatus() {
        // Require authentication
        if (!isAuthenticated()) {
            jsonError('Authentication required', 'AUTH_ERROR', 401);
        }
        
        $userId = getCurrentUserId();
        $hasSubscription = $this->notificationModel->hasActiveSubscription($userId);
        
        jsonSuccess([
            'subscribed' => $hasSubscription,
            'user_id' => $userId
        ]);
    }
    
    /**
     * Export contacts for the current logged-in user as Excel
     * GET /api/export-contacts
     */
    public function exportContacts() {
        if (!isAuthenticated()) {
            jsonError('Authentication required', 'AUTH_ERROR', 401);
        }

        $userId = getCurrentUserId();
        $excelService = new ExcelService();
        
        // Admin can export all contacts, regular users only their own
        if (isAdmin()) {
            $result = $excelService->exportContacts(null); // null = all users
        } else {
            $result = $excelService->exportContacts($userId);
        }

        if (!$result['success']) {
            jsonError($result['message'] ?? 'Export failed', 'EXPORT_ERROR', 500);
        }

        $filePath = $result['file'];
        if (!file_exists($filePath)) {
            jsonError('Export file not found', 'EXPORT_ERROR', 500);
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="my_contacts_' . date('Y-m-d') . '.xlsx"');
        header('Content-Length: ' . filesize($filePath));
        header('Cache-Control: max-age=0');
        readfile($filePath);
        unlink($filePath);
        exit;
    }

    /**
     * Search contacts
     * GET /api/search?q=query
     */
    public function search() {
        // Require authentication
        if (!isAuthenticated()) {
            jsonError('Authentication required', 'AUTH_ERROR', 401);
        }
        
        $query = sanitize($_GET['q'] ?? '');
        $userId = getCurrentUserId();
        $contactModel = new Contact();
        
        // If no query, return contacts based on user type
        if (empty($query)) {
            if (isAdmin()) {
                $contacts = $contactModel->getAll();
            } else {
                $contacts = $contactModel->getByUser($userId);
            }
            jsonSuccess($contacts);
            return;
        }
        
        if (strlen($query) < 2) {
            jsonError('Query must be at least 2 characters', 'VALIDATION_ERROR', 400);
        }
        
        // Search contacts based on user type
        if (isAdmin()) {
            $contacts = $contactModel->search($query);
        } else {
            $contacts = $contactModel->search($query, $userId);
        }
        
        jsonSuccess($contacts);
    }
}
