<?php
require_once __DIR__ . '/_common.php';
require_csrf_unless_get();
list($action, $body) = read_action();

// Device + parent-control rows hold secrets (device_key, pin_code) that a
// viewer-role admin should never see — they'd let the holder impersonate any
// device against the panel or unlock parent controls. Filter at read time.
function devices_redact_for_viewer(array $row) {
    $row['device_key']    = '<hidden>';
    $row['android_id']    = '<hidden>';
    $row['app_device_id'] = '<hidden>';
    if (array_key_exists('pin_code', $row)) $row['pin_code'] = '<hidden>';
    return $row;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (!empty($_GET['id'])) {
        $row = db_one(
            'SELECT d.*, s.plan_id, s.price, s.expired_date, s.is_trial, s.lock,
                    pc.pin_code, pc.parent_control, pc.parent_synced
             FROM devices d
             LEFT JOIN subscriptions   s  ON s.device_id  = d.id
             LEFT JOIN parent_control  pc ON pc.device_id = d.id
             WHERE d.id = ?',
            [(int)$_GET['id']]
        );
        if (!$row) json_error('device not found', 404);
        if (!auth_is_admin()) $row = devices_redact_for_viewer($row);
        json_response(['device' => $row]);
    }
    $rows = db_all(
        'SELECT d.id, d.mac_address, d.android_id, d.device_key, d.app_type, d.app_version,
                d.is_google_pay, d.first_seen_at, d.last_seen_at,
                s.is_trial, s.expired_date, s.plan_id, s.price, s.lock,
                (SELECT COUNT(*) FROM playlists pl WHERE pl.device_id = d.id) AS playlist_count
         FROM devices d
         LEFT JOIN subscriptions s ON s.device_id = d.id
         ORDER BY d.last_seen_at DESC'
    );
    if (!auth_is_admin()) {
        $rows = array_map('devices_redact_for_viewer', $rows);
    }
    json_response(['devices' => $rows]);
}

if ($action === 'create') {
    $mac = strtolower(trim((string)($body['mac_address'] ?? '')));
    if ($mac === '') json_error('Enter a MAC address.');
    if (!preg_match('/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/', $mac)) {
        json_error('Enter a valid MAC address (e.g. AA:BB:CC:DD:EE:FF).');
    }
    if (db_one('SELECT id FROM devices WHERE mac_address = ?', [$mac])) {
        json_error('A device with that MAC is already registered.');
    }
    $device_key = !empty($body['device_key']) ? $body['device_key'] : ('dev-token-' . random_hex(32));
    try {
        $id = db_insert(
            'INSERT INTO devices (mac_address, android_id, app_device_id,
                                  device_key, app_type, app_version, is_google_pay)
             VALUES (?, ?, ?, ?, ?, ?, ?)',
            [$mac,
             isset($body['android_id']) ? $body['android_id'] : null,
             isset($body['app_device_id']) ? $body['app_device_id'] : null,
             $device_key,
             isset($body['app_type']) ? $body['app_type'] : 'phone',
             isset($body['app_version']) ? $body['app_version'] : '4.3',
             truthy($body['is_google_pay'] ?? 0)]
        );
        db_exec('INSERT INTO subscriptions  (device_id) VALUES (?)', [$id]);
        db_exec('INSERT INTO parent_control (device_id) VALUES (?)', [$id]);
        json_response(['ok' => true, 'id' => $id, 'device_key' => $device_key]);
    } catch (Exception $e) {
        panel_log_exception($e, ['context' => 'devices.create', 'mac' => $mac]);
        json_error('Could not add the device. Try again.');
    }
}

if ($action === 'update') {
    if (empty($body['id'])) json_error('missing id');
    $mac = strtolower(trim((string)($body['mac_address'] ?? '')));
    if ($mac !== '' && !preg_match('/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/', $mac)) {
        json_error('Enter a valid MAC address (e.g. AA:BB:CC:DD:EE:FF).');
    }
    db_exec(
        'UPDATE devices SET mac_address = ?, android_id = ?, app_device_id = ?,
                            app_type = ?, app_version = ?, is_google_pay = ?,
                            last_seen_at = ?
         WHERE id = ?',
        [$mac,
         $body['android_id']    ?? null,
         $body['app_device_id'] ?? null,
         $body['app_type']      ?? 'phone',
         $body['app_version']   ?? '4.3',
         truthy($body['is_google_pay'] ?? 0),
         unix_now(),
         (int)$body['id']]
    );
    json_response(['ok' => true]);
}

if ($action === 'delete') {
    if (empty($body['id'])) json_error('missing id');
    db_exec('DELETE FROM devices WHERE id = ?', [(int)$body['id']]);
    json_response(['ok' => true]);
}

if ($action === 'delete_user_row') {
    // Row-level delete used by services_clients.php. Each visible row is a
    // unique (device, playlist) pair. The intent when the operator clicks
    // the trash icon is:
    //   - remove THIS playlist so the app can't auto-login with it
    //   - if that was the only playlist on the MAC, remove the MAC too so
    //     it's gone from the list
    //   - if the same MAC has OTHER playlists (rendered as their own rows),
    //     leave the MAC + those other playlists intact
    $device_id   = isset($body['device_id'])   ? (int)$body['device_id']   : 0;
    $playlist_id = isset($body['playlist_id']) ? (int)$body['playlist_id'] : 0;
    if ($device_id <= 0) json_error('missing device_id');

    $pdo = panel_db();
    $pdo->beginTransaction();
    try {
        if ($playlist_id > 0) {
            $stmt = $pdo->prepare('DELETE FROM playlists WHERE id = ? AND device_id = ?');
            $stmt->execute([$playlist_id, $device_id]);
        }
        $rem = $pdo->prepare('SELECT COUNT(*) FROM playlists WHERE device_id = ?');
        $rem->execute([$device_id]);
        $remaining = (int)$rem->fetchColumn();
        $device_deleted = false;
        if ($remaining === 0) {
            $del = $pdo->prepare('DELETE FROM devices WHERE id = ?');
            $del->execute([$device_id]);
            $device_deleted = ($del->rowCount() > 0);
        }
        $pdo->commit();
        json_response(['ok' => true, 'device_deleted' => $device_deleted, 'remaining_playlists' => $remaining]);
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        json_error('delete failed: ' . $e->getMessage(), 500);
    }
}

if ($action === 'rotate_key') {
    if (empty($body['id'])) json_error('missing id');
    $new = 'dev-token-' . random_hex(32);
    db_exec('UPDATE devices SET device_key = ? WHERE id = ?', [$new, (int)$body['id']]);
    json_response(['ok' => true, 'device_key' => $new]);
}

json_error('unknown action', 400);
