<?php
/**
 * Device Unregister API - Remove FCM device token on logout
 */
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'] ?? '');

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

try {
    dbQuery(
        "UPDATE app_devices SET is_active = 0 WHERE user_id = ? AND device_token = ?",
        [$userId, $deviceToken]
    );

    jsonSuccess('Device unregistered successfully');

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