<?php

namespace App\Http\Controllers\Api\V1\Student;

use App\Http\Controllers\Api\V1\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Models\DeviceToken;

class DeviceTokenController extends BaseController
{
    /**
     * Register or update device token for push notifications.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        try {
            $user = Auth::user();
            
            $validated = $request->validate([
                'device_token' => 'required|string',
                'device_type' => 'nullable|string|in:android,ios,web',
                'device_id' => 'nullable|string',
                'app_version' => 'nullable|string',
            ]);

            // Check if token already exists for this user
            $deviceToken = DeviceToken::where('user_id', $user->id)
                ->where('device_token', $validated['device_token'])
                ->first();

            if ($deviceToken) {
                // Update existing token
                $deviceToken->update([
                    'device_type' => $validated['device_type'] ?? $deviceToken->device_type,
                    'device_id' => $validated['device_id'] ?? $deviceToken->device_id,
                    'app_version' => $validated['app_version'] ?? $deviceToken->app_version,
                    'is_active' => true,
                    'last_used_at' => now(),
                ]);
            } else {
                // Create new token
                $deviceToken = DeviceToken::create([
                    'user_id' => $user->id,
                    'device_token' => $validated['device_token'],
                    'device_type' => $validated['device_type'] ?? 'android',
                    'device_id' => $validated['device_id'],
                    'app_version' => $validated['app_version'],
                    'is_active' => true,
                    'last_used_at' => now(),
                ]);
            }

            return $this->success([
                'id' => $deviceToken->id,
                'device_token' => $deviceToken->device_token,
                'device_type' => $deviceToken->device_type,
                'registered_at' => $deviceToken->created_at,
            ], 'Device token registered successfully');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return $this->error('Validation failed', $e->errors(), 422);
        } catch (\Exception $e) {
            Log::error('Device Token Registration API error: ' . $e->getMessage());
            return $this->error('An error occurred while registering device token.', null, 500);
        }
    }

    /**
     * Unregister device token (logout or uninstall).
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function unregister(Request $request)
    {
        try {
            $user = Auth::user();
            
            $validated = $request->validate([
                'device_token' => 'required|string',
            ]);

            $deviceToken = DeviceToken::where('user_id', $user->id)
                ->where('device_token', $validated['device_token'])
                ->first();

            if ($deviceToken) {
                $deviceToken->update(['is_active' => false]);
            }

            return $this->success(null, 'Device token unregistered successfully');
        } catch (\Exception $e) {
            Log::error('Device Token Unregistration API error: ' . $e->getMessage());
            return $this->error('An error occurred while unregistering device token.', null, 500);
        }
    }
}

