<?php
/**
 * Device Registration API - Register FCM device token for push notifications
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonError('Method not allowed', 405);
}

if (!isset($_SESSION['user_id'])) {
    jsonError('Not authenticated', 401);
}

$userId = $_SESSION['user_id'];
$data = json_decode(file_get_contents('php://input'), true);

$deviceToken = trim($data['device_token'] ?? '');
$deviceType  = $data['device_type'] ?? 'android';
$deviceModel = $data['device_model'] ?? null;
$appVersion  = $data['app_version'] ?? null;
$osVersion   = $data['os_version'] ?? null;

if (empty($deviceToken)) {
    jsonError('Device token is required');
}

try {
    // Check if token already exists for this user
    $existing = dbFetch(
        "SELECT id FROM app_devices WHERE user_id = ? AND device_token = ?",
        [$userId, $deviceToken]
    );

    if ($existing) {
        // Update existing record
        dbQuery(
            "UPDATE app_devices SET is_active = 1, device_model = ?, app_version = ?, os_version = ?, updated_at = NOW() WHERE id = ?",
            [$deviceModel, $appVersion, $osVersion, $existing['id']]
        );
    } else {
        // Deactivate old tokens for this user (keep max 3 devices)
        $activeCount = dbCount('app_devices', 'user_id = ? AND is_active = 1', [$userId]);
        if ($activeCount >= 3) {
            dbQuery(
                "UPDATE app_devices SET is_active = 0 WHERE user_id = ? AND is_active = 1 ORDER BY updated_at ASC LIMIT 1",
                [$userId]
            );
        }

        // Insert new device
        dbInsert('app_devices', [
            'user_id'      => $userId,
            'device_token' => $deviceToken,
            'device_type'  => $deviceType,
            'device_model' => $deviceModel,
            'app_version'  => $appVersion,
            'os_version'   => $osVersion,
            'is_active'    => 1
        ]);
    }

    jsonSuccess('Device registered successfully');

} catch (Exception $e) {
    error_log("Device Register Error: " . $e->getMessage());
    jsonError('Failed to register device');
}
