<?php

namespace App\Controllers;

use App\Models\DeviceTokenModel;
use App\Libraries\FcmNotificationService;
use CodeIgniter\RESTful\ResourceController;

class Notifications extends ResourceController
{
    protected $deviceTokenModel;
    protected $fcmService;
    protected $format = 'json';

    public function __construct()
    {
        $this->deviceTokenModel = new DeviceTokenModel();
    }

    /**
     * Register FCM token for a user
     * POST /api/notifications/register-token
     * 
     * Expected JSON body:
     * {
     *   "msisdn": "256700000000",
     *   "fcm_token": "...",
     *   "device_type": "android" // optional: android, ios, web
     * }
     */
    public function registerToken()
    {
        log_message('info', 'FCM registerToken called');
        log_message('info', 'Request Method: ' . $this->request->getMethod());
        log_message('info', 'Request Body: ' . $this->request->getBody());
        
        $data = $this->request->getJSON(true);
        
        log_message('info', 'Parsed JSON: ' . json_encode($data));
        
        if (!isset($data['msisdn']) || !isset($data['fcm_token'])) {
            log_message('error', 'Missing required fields');
            return $this->fail('Missing required fields: msisdn and fcm_token', 400);
        }
        
        $msisdn = $data['msisdn'];
        $fcmToken = $data['fcm_token'];
        $deviceType = $data['device_type'] ?? 'android';
        
        // Validate device type
        if (!in_array($deviceType, ['android', 'ios', 'web'])) {
            return $this->fail('Invalid device_type. Must be android, ios, or web', 400);
        }
        
        try {
            $result = $this->deviceTokenModel->registerToken($msisdn, $fcmToken, $deviceType);
            
            if ($result) {
                return $this->respondCreated([
                    'status' => 'success',
                    'message' => 'FCM token registered successfully',
                    'data' => [
                        'msisdn' => $msisdn,
                        'device_type' => $deviceType
                    ]
                ]);
            } else {
                return $this->failServerError('Failed to register FCM token');
            }
        } catch (\Exception $e) {
            log_message('error', 'FCM token registration error: ' . $e->getMessage());
            return $this->failServerError('An error occurred while registering token: ' . $e->getMessage());
        }
    }

    /**
     * Deactivate FCM token (e.g., on logout)
     * POST /api/notifications/deactivate-token
     * 
     * Expected JSON body:
     * {
     *   "fcm_token": "..."
     * }
     */
    public function deactivateToken()
    {
        $data = $this->request->getJSON(true);
        
        if (!isset($data['fcm_token'])) {
            return $this->fail('Missing required field: fcm_token', 400);
        }
        
        try {
            $result = $this->deviceTokenModel->deactivateToken($data['fcm_token']);
            
            if ($result) {
                return $this->respond([
                    'status' => 'success',
                    'message' => 'FCM token deactivated successfully'
                ]);
            } else {
                return $this->failNotFound('Token not found');
            }
        } catch (\Exception $e) {
            log_message('error', 'FCM token deactivation error: ' . $e->getMessage());
            return $this->failServerError('An error occurred while deactivating token');
        }
    }

    /**
     * Test sending a notification (for testing purposes)
     * POST /api/notifications/test-send
     * 
     * Expected JSON body:
     * {
     *   "msisdn": "256700000000",
     *   "title": "Test Title",
     *   "message": "Test Message"
     * }
     */
    public function testSend()
    {
        // Only allow in development environment
        if (ENVIRONMENT !== 'development') {
            return $this->failForbidden('This endpoint is only available in development mode');
        }
        
        $data = $this->request->getJSON(true);
        
        if (!isset($data['msisdn']) || !isset($data['title']) || !isset($data['message'])) {
            return $this->fail('Missing required fields: msisdn, title, message', 400);
        }
        
        try {
            $this->fcmService = new FcmNotificationService();
            $result = $this->fcmService->sendToUser(
                $data['msisdn'],
                $data['title'],
                $data['message'],
                $data['data'] ?? []
            );
            
            return $this->respond([
                'status' => 'success',
                'message' => 'Test notification sent',
                'result' => $result
            ]);
        } catch (\Exception $e) {
            log_message('error', 'Test notification error: ' . $e->getMessage());
            return $this->failServerError('An error occurred while sending notification: ' . $e->getMessage());
        }
    }

    /**
     * Get user's registered devices
     * GET /api/notifications/devices?msisdn=256700000000
     */
    public function getDevices()
    {
        $msisdn = $this->request->getGet('msisdn');
        
        if (!$msisdn) {
            return $this->fail('Missing required parameter: msisdn', 400);
        }
        
        try {
            $tokens = $this->deviceTokenModel->getUserTokens($msisdn);
            
            // Don't expose full tokens, just return device info
            $devices = array_map(function($token) {
                return [
                    'device_type' => $token['device_type'],
                    'created_at' => $token['created_at'],
                    'updated_at' => $token['updated_at']
                ];
            }, $tokens);
            
            return $this->respond([
                'status' => 'success',
                'data' => $devices
            ]);
        } catch (\Exception $e) {
            log_message('error', 'Get devices error: ' . $e->getMessage());
            return $this->failServerError('An error occurred while fetching devices');
        }
    }
}

